4

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, but I am getting an error saying AttributeError: 'datetime.datetime' object has no attribute 'timestamp'
I have only imported datetime
timestamp() is new in version 3.3. Which version of Python do you use?
I am using python 2.7
For versions without .timestamp() I prefer time.mktime(dt.timetuple()).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.