Search code examples
pythondatetimetimestamprfc3339

How to convert API timestamp into python datetime object


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...

Solution

  • 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.