coja7723 coja7723 - 2 years ago 298
Python Question

utc string to unix time conversion python

I have a list of UTC time stamps stored as string format as follows:


Is there a function in python to convert these strings to unix time? I have tried:

dt = datetime.datetime.utcnow()
(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.

Answer Source

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:


Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time().


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download