Sunday, August 15, 2010

Notes - Python time string to timestamp

>>> from datetime import datetime, date, time
>>> import time as _time
>>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)
>>> tt
(2006, 11, 21, 16, 30, 0, 1, 0, -1)
>>> stamp = _time.mktime(tt)
>>> stamp
1164123000.0
>>> o = datetime.fromtimestamp(stamp)
>>> print o
2006-11-21 16:30:00

More info with all string codes for date/time here:
http://docs.python.org/library/time.html#time.strftime

No comments:

 

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.