0% found this document useful (0 votes)
7K views

Convert Python UTC Datetime Object To UNIX Timestamp

python

Uploaded by

bluebird1969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views

Convert Python UTC Datetime Object To UNIX Timestamp

python

Uploaded by

bluebird1969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

10/27/2014

How to convert Python UTC datetime object to UNIX timestamp

Ruslan's Blog
The harder you work the luckier you get
HOME
ABOUT
To search, type and hit enter

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.
1
2
3
4

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


1
2
3

>>> import calendar


>>> calendar.timegm(d.utctimetuple())
1311218002

Lets verify it:


1
2

$ date -ud @1311218002


Thu Jul 21 03:13:22 UTC 2011

Looks fine, but I cant 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.
{ 13 comments read them below or add one }

Michael July 21, 2011 at 6:05 AM


http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/

1/6

10/27/2014

How to convert Python UTC datetime object to UNIX timestamp

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)
http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/

2/6

10/27/2014

How to convert Python UTC datetime object to UNIX timestamp

>>> time.mktime(d.timetuple())
1311236002.0
[/sourcecode]
Reply

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

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

Cat March 21, 2012 at 11:59 PM


http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/

3/6

10/27/2014

How to convert Python UTC datetime object to UNIX timestamp

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!
Im thinking I dont 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 Im 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
Name *
E-mail *
http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/

4/6

10/27/2014

How to convert Python UTC datetime object to UNIX timestamp

Website

Submit

Notify me of follow-up comments by email.


Notify me of new posts by email.
{ 2 trackbacks }
Python Links for the Week: 7/22/2011 The Mouse Vs. The Python
How to convert Python UTC datetime object to UNIX timestamp | Code Dreams
Previous post: Nice logging feature in Erlang
Next post: Parsing fixed length file records with Python

Follow Me

Categories
python (72)
emacs (28)
bash (18)
erlang (14)
pyramid (3)
uncategorized (2)

Recent Posts
How to Pretty Print XML with lxml
Need for Speed SENDFILE System Call
http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/

5/6

10/27/2014

How to convert Python UTC datetime object to UNIX timestamp

Self-Pipe Trick
SIGPIPE 101
Simple Examples of Concurrent Server Design in Python

Recent Comments
Igor Kupczynski on How to Pretty Print XML with lxml
AnneTheAgile on BASH history incremental search forward
cesium62 on How to convert Python UTC datetime object to UNIX timestamp
Aleksei on Urlencode and urldecode from a command line
vasya on Urlencode and urldecode from a command line

Archives
May 2014
June 2012
May 2012
April 2012
March 2012
February 2012
January 2012
December 2011
July 2011
June 2011
May 2011
April 2011
March 2011
February 2011
January 2011
December 2010
November 2010
October 2010
September 2010
June 2010
April 2010
February 2010
December 2009
November 2009
October 2009
April 2009
March 2009
April 2008
November 2007
October 2007
September 2007
August 2007
Copyright 2012 - Ruslan Spivak

http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/

6/6

You might also like