2

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?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
NIH
  • 151
  • 2
  • 2
  • 8
  • related: [Convert timestamps with offset to datetime obj using strptime](http://stackoverflow.com/q/12281975/4279) – jfs Mar 27 '15 at 09:21

2 Answers2

12

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.

Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69
0

I highly recommend python-dateutil library, it allows conversion of multiple datetime formats from raw strings into datetime objects with/without timezone set

>>> from dateutil.parser import parse
>>> parse('2012-04-30T23:08:56+00:00')

datetime.datetime(2012, 4, 30, 23, 8, 56, tzinfo=tzutc())
DmitrySemenov
  • 9,204
  • 15
  • 76
  • 121