I know how to do it in C and Java, but I don't know a quick way of converting year/month/day/hour/min/second to the # of seconds since the Jan 1 1970 epoch.
Can someone help me?
So far I've figured out how to create a datetime
object but I can't seem to get the elapsed # seconds since the epoch.
(edit: my question is the inverse of this other one: Python: Seconds since epoch to relative date)
Use timetuple
or utctimetuple
method to get time tuple and convert it to timestamp using time.mktime
>>> import datetime
>>> dt = datetime.datetime(2011, 12, 13, 10, 23)
>>> import time
>>> time.mktime(dt.timetuple())
1323793380.0
There is a nice bug related to it http://bugs.python.org/issue2736, this is interesting read and anybody trying to convert to timestamp should read this. According to that thread correct way is
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)