datetime seems to be broken WRT timezones (even when you add them)
Chris Angelico
rosuav at gmail.com
Mon Feb 10 19:33:54 EST 2020
On Tue, Feb 11, 2020 at 11:17 AM Python <python at bladeshadow.org> wrote:
>
> On Tue, Feb 11, 2020 at 11:04:28AM +1100, Chris Angelico wrote:
> > On Tue, Feb 11, 2020 at 10:42 AM Python <python at bladeshadow.org> wrote:
> > > Now, you can instantiate a datetime.datetime object with the times you
> > > want, and pass an instance of this class as the tzinfo argument to the
> > > constructor. Also no problem:
> >
> > Rather than try to create your own GMT() object, have you considered
> > using datetime.timezone.utc ? I tested it in your examples and it
> > works just fine.
>
> Not here it doesn't:
>
> >>> import datetime
> >>> dt = datetime.datetime(2020, 1, 31, 1, 30, 45, 987654, datetime.timezone.utc)
> >>> print(dt)
> 2020-01-31 01:30:45.987654+00:00
> >>> print(dt.strftime("%s"))
> 1580452245
>
> That's the same erroneous result from my example. The correct value
> is again 1580434245. Unless you've done something subtlely
> different...
I haven't verified the arithmetic or that the date command is actually
giving the result you want/expect here, but in my testing, I got what
looked like correct results. However, instead of using the
undocumented and unsupported strftime %s format code, I've been using
the timestamp() method:
https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp
rosuav at sikorsky:~$ cat utctest.py
import datetime
dt = datetime.datetime(2020, 1, 31, 1, 30, 45, 987654, datetime.timezone.utc)
print(dt)
print(dt.timestamp())
rosuav at sikorsky:~$ python3.9 utctest.py
2020-01-31 01:30:45.987654+00:00
1580434245.987654
rosuav at sikorsky:~$ python3.8 utctest.py
2020-01-31 01:30:45.987654+00:00
1580434245.987654
rosuav at sikorsky:~$ python3.7 utctest.py
2020-01-31 01:30:45.987654+00:00
1580434245.987654
rosuav at sikorsky:~$ python3.6 utctest.py
2020-01-31 01:30:45.987654+00:00
1580434245.987654
rosuav at sikorsky:~$ python3.5 utctest.py
2020-01-31 01:30:45.987654+00:00
1580434245.987654
rosuav at sikorsky:~$ python3.4 utctest.py
2020-01-31 01:30:45.987654+00:00
1580434245.987654
My interpretation is that, on your platform, strftime("%s") is broken
in the presence of tzinfo.
> Also it's only available on Python3, which may not be the end of the
> world, but the tool I'm working on is--for the moment at
> least--expected to work on both python2.7 and 3. But it's irrelevant
> if it doesn't give the correct result, which seems to still be the
> case.
>
That may be your problem, but it's not mine, and I'm not going to
attempt to answer for Python 2.
ChrisA
More information about the Python-list
mailing list