khue bui khue bui - 3 years ago 131
Python Question

Format of "2016-10-22T16:27:54+0000" to convert to datetime

I want to convert a string to datetime.

The string is:

date_created = "2016-10-22T16:27:54+0000"

And I am trying to convert that with:

datetime.strptime(date_created, '%y-%m-%dT%H:%M:%S+0000')

but the format does not match.

So, what is the correct format to use?

Answer Source

%y matches a year with two digits, but your input uses 4 digits. Use %Y instead:

>>> from datetime import datetime
>>> date_created = "2016-10-22T16:27:54+0000"
>>> datetime.strptime(date_created, '%Y-%m-%dT%H:%M:%S+0000')
datetime.datetime(2016, 10, 22, 16, 27, 54)

From the strftime() and strptime() Behavior section:

Year without century as a zero-padded decimal number.
00, 01, ..., 99

%Y Year with century as a decimal number.
0001, 0002, ..., 2013, 2014, ..., 9998, 9999

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download