Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a unix timestamp that doesn't adjust for localtime?

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.

like image 404
sheats Avatar asked Jul 23 '10 03:07

sheats


1 Answers

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 the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.

like image 60
Greg Hewgill Avatar answered Oct 17 '22 19:10

Greg Hewgill