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