I am trying to port some code from python2 to python3. I am having trouble when converting some code using date/time manipulations.
Python2.7
Python 2.7.13 (default, Apr 19 2017, 02:44:33)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import os
>>> os.environ['TZ'] = 'UTC'
>>> datetime.datetime.fromtimestamp(1461085831)
datetime.datetime(2016, 4, 19, 17, 10, 31)
Python3.6
Python 3.6.1 (default, Apr 19 2017, 21:58:41)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import os
>>> os.environ['TZ'] = 'UTC'
>>> datetime.datetime.fromtimestamp(1461085831)
datetime.datetime(2016, 4, 19, 22, 40, 31)
The result for python2 = (2016, 4, 19, 17, 10, 31)
whereas for python3 = (2016, 4, 19, 22, 40, 31)
.
Why is this difference, and how should I overcome this?
This is a little bit tricky. According to my knowledge, this only happen with python 3.6. For short, you need to call time.tzset
after set TZ
environment. I've encountered it sometime ago (I don't remember exactly), and I don't have pre-3.6 python to test, so please bear with me. I've just checked this issue on my colleague's python3.5
, it works as expected (without putting time.tzset()
)
The time.tzset
docs say:
Reset the time conversion rules used by the library routines. The environment variable TZ specifies how this is done. It will also set the variables tzname (from the TZ environment variable), timezone (non-DST seconds West of UTC), altzone (DST seconds west of UTC) and daylight (to 0 if this timezone does not have any daylight saving time rules, or to nonzero if there is a time, past, present or future when daylight saving time applies).
Just put the time.tzset()
:
EDITED: I've just made some search, this behavior had been (mistakenly) reported as a bug: datetime in Python 3.6+ no longer respects 'TZ' environment variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With