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

Jon Ribbens jon+usenet at unequivocal.eu
Mon Feb 10 19:59:04 EST 2020


On 2020-02-10, Python <python at bladeshadow.org> 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')
    '1580452245'
    >>> import os
    >>> os.environ['TZ'] = 'UTC'
    >>> dt.strftime('%s')
    '1580434245'

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()



More information about the Python-list mailing list