khue bui khue bui - 1 month ago 12
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

%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:

%y
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

Comments