How to convert Python UTC datetime object to UNIX timestamp

by Ruslan Spivak on July 20, 2011

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.

{ 11 comments… read them below or add one }

Michael July 21, 2011 at 6:05 AM

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′

Reply

Ruslan Spivak July 21, 2011 at 8:00 PM

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]

Reply

Christoph Burgmer July 21, 2011 at 2:11 PM

>>> 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.

Reply

Ruslan Spivak July 21, 2011 at 8:09 PM

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]

Reply

fylefou July 22, 2011 at 1:54 AM

So why so much way to do it ?
why not “totimestamp” in datetime like the “fromtimestamp” method?

Reply

Ruslan Spivak July 22, 2011 at 5:42 AM

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.

Reply

Cat March 21, 2012 at 11:59 PM

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.

Reply

Benjamin Riggs December 16, 2012 at 7:43 PM

If you want the current timestamp, “calendar.timegm(time.gmtime())” is cleaner (and quicker) than utcnow().

Reply

Rufus V. Smith May 31, 2013 at 3:29 PM

My day was like yours, CAT!
I’m thinking “I don’t want a stinkin’ tuple!”
I can get tuples from timestamps easy!
I can parse a string into a tuple easy!
I just want a way to parse a string (“mm/dd/yy HH:MM:SS”) into a stinkin’ timestamp!
Is that too much to ask – it should be easy!
(actually I’m starting with a wx.DateTime)

After reading this thread, I ended up with:

time.mktime(time.strptime(str(dvalue),”%m/%d/%y %H:%M:%S”))

Is this really the one good way to do it?

Reply

Abe Kazemzadeh June 10, 2013 at 6:29 PM

Thanks! I was having a lot of trouble figuring out the right way to do this.

Reply

Simon July 12, 2013 at 11:09 AM

Thanks! This was a huge help!!!!
Writing an open source FTP sync tool (dropbox clone) so timezones are a huge factor!

Reply

Speak your mind

{ 2 trackbacks }

Previous post:

Next post: