Convert Python Datetime To Epoch With Strftime


Answer :

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



>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0


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



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





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



Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior 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')
'1333234800'


I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).



>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400


import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android SDK Location Should Not Contain Whitespace, As This Cause Problems With NDK Tools