So, I have datetime objects in UTC, and I want to convert them to UTC timestamps. The problem is that time.mktime makes adjustments for localtime.
So here is the code:
import os
import pytz
import time
import datetime
epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1))
print time.mktime(epoch.timetuple())
os.environ['TZ'] = 'UTC+0'
time.tzset()
print time.mktime(epoch.timetuple())
Here are some results:
Python 2.6.4 (r264:75706, Dec 25 2009, 08:52:16)
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import pytz
>>> import time
>>> import datetime
>>>
>>> epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1))
>>> print time.mktime(epoch.timetuple())
25200.0
>>>
>>> os.environ['TZ'] = 'UTC+0'
>>> time.tzset()
>>> print time.mktime(epoch.timetuple())
0.0
Thus, it is obvious that if the system is in UTC, not a problem, but when it is not, it is a problem. Setting the environment variable and calling time.tzset works, but is it safe? I do not want to configure it for the whole system.
Is there any other way to do this? Or it's safe to call time.tzset this way.
source
share