Fix Python – Convert python datetime to epoch with strftime


Asked By – Noel

I have a time in UTC from which I want the number of seconds since epoch.

I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.


1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.

So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?

How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).

Now we will see solution for issue: Convert python datetime to epoch with strftime


If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,4,1,0,0) - datetime.datetime(1970,1,1)).total_seconds()

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()

Why you should not use datetime.strftime('%s')

Python doesn’t actually support %s as an argument to strftime (if you check at it’s not in the list), the only reason it’s working is because Python is passing the information to your system’s strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')

This question is answered By – jleahy

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0