[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

datetime seems to be broken WRT timezones (even when you add them)

On 2020-02-10, Python <python at> wrote:
> So far, so good.  However, when you go to use this object, the time it
> represents is in fact wrong.

Unsurprisingly for a language feature that's been around for nearly
17 years, no it isn't.

> For example:
>>>> print dt.strftime("%s")
> 1580452245

That's asking your libc's strftime to process the time through the
"%s" format code, which has no defined behaviour under either Python
or POSIX. If you're using GNU libc however then it uses the time
information given and the timezone from the 'TZ' environment variable
and returns seconds since the Unix epoch:

    >>> dt.strftime('%s')
    >>> import os
    >>> os.environ['TZ'] = 'UTC'
    >>> dt.strftime('%s')

If you need to know the seconds since the epoch then in Python 3.3+
you can do that with dt.timestamp(). In Python 2.7 you can use the UTC
class you created:

    (dt - datetime(1970, 1, 1, 0, 0, 0, 0, GMT())).total_seconds()