How to convert API timestamp into python datetime object

2.4k Views Asked by At

I am getting the following string from an API call:

s = '2014-12-11T20:46:12Z'

How would I then convert this into a python object? Is there an easy way, or should I be splitting up the string, for example:

year = s.split('-')[0]
month = s.split('-')[1]
day = s.split('-')[2]
time = s.split('T')[1]
...etc...
2

There are 2 best solutions below

0
On BEST ANSWER

You can use the datetime.datetime.strptime function:

>>> from datetime import datetime
>>> s = '2014-12-11T20:46:12Z'
>>> datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 12, 11, 20, 46, 12)
>>>

For a complete list of the available format codes, see strftime() and strptime() Behavior.

1
On

Using datetime should do it, recently I found arrow is also a good library to deal with dates.

import arrow
s = '2014-12-11T20:46:12Z'
your_date = arrow.get(s)
print(t.year)  # 2014
print(t.hour)  # 20