I seem to get this question every half a year and every time I have difficulties remembering how to do it.
>>> from datetime import datetime >>> d = datetime.utcnow() >>> d datetime.datetime(2011, 7, 21, 3, 13, 22, 259901)
So here is the snippet that I use to convert datetime to timestamp:
>>> import calendar >>> calendar.timegm(d.utctimetuple()) 1311218002
Let’s verify it:
$ date -ud @1311218002 Thu Jul 21 03:13:22 UTC 2011
Looks fine, but I can’t for the life of me understand why the function timegm is part of the calendar module.
From Python official documentation:
- 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.
If you enjoyed this post why not subscribe via email or my RSS feed and get the latest updates immediately.
You can also follow me on GitHub or Twitter.



{ 8 comments… read them below or add one }
datetime objects can do that as well using `strftime`:
In [7]: d = datetime.datetime(2011, 7, 21, 3, 13, 22, 259901)
In [8]: d.strftime(‘%s’)
Out[8]: ’1311210802′
Unfortunately timezone-aware datetime objects (UTC) incorrectly calculate UNIX timestamp:
[sourcecode language="python"]
>>> import pytz
>>> import datetime
>>> utc = pytz.timezone(‘UTC’)
>>> toronto = pytz.timezone(‘America/Toronto’)
>>> a = datetime.datetime(2011, 7, 21, 3, 13, 22, tzinfo=utc)
>>> b = a.astimezone(toronto)
>>> a.strftime(‘%s’)
’1311236002′
>>> b.strftime(‘%s’)
’1311218002′
[/sourcecode]
>>> import datetime
>>> import time
>>> d = datetime.datetime(2011, 7, 21, 3, 13, 22, 259901)
>>> time.mktime(d.timetuple())
1311210802.0
Probably the more basic way.
time.mktime(t) returns timestamp in local time:
[sourcecode language="python"]
>>> import pytz
>>> import datetime
>>> import time
>>>
>>> utc = pytz.timezone(‘UTC’)
>>> d = datetime.datetime(2011, 7, 21, 3, 13, 22, tzinfo=utc)
>>> time.mktime(d.timetuple())
1311236002.0
[/sourcecode]
So why so much way to do it ?
why not “totimestamp” in datetime like the “fromtimestamp” method?
Well, technically there are not many correct ways to do it. But I agree with the API question, having that call would make conversion process clear and unambiguous.
Thank God for this post, I had wasted half a day looking for an easy way to get the UTC timestamp before running into this.
If you want the current timestamp, “calendar.timegm(time.gmtime())” is cleaner (and quicker) than utcnow().
{ 2 trackbacks }