Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

utc string to unix time conversion python

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.

like image 407
coja7723 Avatar asked Oct 15 '25 16:10

coja7723


1 Answers

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

like image 136
Laurent LAPORTE Avatar answered Oct 17 '25 05:10

Laurent LAPORTE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!