I have a list of UTC time stamps stored as string format as follows:
'20170124T1815'
Is there a function in python to convert these strings to unix time? I have tried:
dt = datetime.datetime.utcnow()
calendar.timegm(dt.utctimetuple())
(datetime.datetime.utcnow('20170127T2131').strftime('%Y-%m-%d %H:%M:%S'))
but these have not been working for me as these functions are not meant to take arguments.
You need to convert the string '20170124T1815' to a datetime instance:
import datetime
dt = datetime.datetime.strptime('20170124T1815', '%Y%m%dT%H%M')
Then use timestamp()
method to convert to UNIX time:
ut = dt.timestamp()
# -> 1485281700.0
The documentation:
datetime.timestamp()
Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by
time.time()
.
EDIT
For Python version < 3.3, you can use:
ut = (dt - datetime.datetime(1970, 1, 1)).total_seconds()
Or, you can use:
import time
ut = time.mktime(dt.timetuple())
Thanks to Peter DeGlopper