Convert UTC time to python datetime

NIH picture NIH · Dec 1, 2012 · Viewed 10.3k times · Source

I have numerous UTC time stamps in the following format: 2012-04-30T23:08:56+00:00 I want to convert them to python datetime objects but am having trouble.

My code:

for time in data:
    pythondata[i]=datetime.strptime(time,"%y-%m-%dT%H:%M:%S+00:00")

I get the following error:

ValueError: time data '2012-03-01T00:05:55+00:00' does not match format '%y-%m-%dT%H:%M:%S+00:00'

It looks like I have the proper format, so why doesn't this work?

Answer

Jon Gauthier picture Jon Gauthier · Dec 1, 2012

Change the year marker in your time format string to %Y:

time = '2012-03-01T00:05:55+00:00'
datetime.strptime(time, "%Y-%m-%dT%H:%M:%S+00:00")
# => datetime.datetime(2012, 3, 1, 0, 5, 55)

See strftime() and strptime() behavior.