So I have datetime objects in UTC time and I want to convert them to UTC timestamps. The problem is, time.mktime makes adjustments for localtime.
So here is some 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 is some output:
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
So obviously if the system is in UTC time no problem, but when it's not, it is a problem. Setting the environment variable and calling time.tzset works but is that safe? I don't want to adjust it for the whole system.
Is there another way to do this? Or is it safe to call time.tzset this way.
The calendar
module contains calendar.timegm
which solves this problem.
calendar.timegm
(tuple)
An unrelated but handy function that takes a time tuple such as returned by the
gmtime()
function in thetime
module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact,time.gmtime()
andtimegm()
are each others’ inverse.
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