1

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...
jfs
  • 399,953
  • 195
  • 994
  • 1,670
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

2

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

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
xbb
  • 2,073
  • 1
  • 19
  • 34
  • I wish I knew about Arrow like 4 years ago. That probably just saved me 30 minutes of fiddling with a weird time format. – sudo Feb 21 '18 at 00:15