Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python2 vs Python3: Different result when converting to datetime from timestamp

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?

like image 345
Arpit Kathuria Avatar asked Nov 01 '18 06:11

Arpit Kathuria


1 Answers

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

See the results

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

like image 77
enamoria Avatar answered Sep 20 '22 00:09

enamoria