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())

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:

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.

{ 13 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′


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’)
>>> b.strftime(‘%s’)


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())

Probably the more basic way.


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())


cesium62 August 14, 2014 at 6:35 PM

There is no such thing as a “timestamp in local time”. A timestamp is the number of seconds since the epoch and the epoch is specified in UTC.

So, are you saying that time.mktime ignores the timezone on the timetuple and uses the host local timezone instead?


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?


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.


Phlip July 20, 2014 at 9:24 PM

This is fixed as you suggest in Python 3.3, which now has a “datetime.timestamp()” method to return the timestamp (and yes, it handles timezones correctly, giving the number of seconds since epoch UTC).

But for earlier versions of Python (including even the latest Python2) you need to do it like the post here says.

As an alternative, timestamp() is actually implemented for timezone-aware datetime objects in the library in a rather direct manner:
EPOCH = datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
return (d – EPOCH).total_seconds()


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.


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


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?


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.


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!


Speak your mind

{ 2 trackbacks }

Previous post:

Next post: