17

I am trying to convert a unicode object to a datetime object.

I read through the documentation: http://docs.python.org/2/library/time.html#time.strptime

and tried

datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%SZ') 

but I get the error message ValueError: time data '2014-01-15T01:35:30.314Z' does not match format '%Y-%m-%dT%H:%M:%SZ'

Any feedback on what is the proper format?

I appreciate the time and expertise.

bbrooke
  • 2,267
  • 10
  • 33
  • 41
  • You're reading the wrong documentation. While `time.strptime` and `datetime.datetime.strptime` are obviously _similar_ functions, they're (as on 2.6+) implemented entirely separately, and have different lists of why they can handle. (`time` just calls your platform's C library; `datetime` manually handles additional format directives are even if your platform doesn't.) – abarnert Jan 16 '14 at 02:02

2 Answers2

35

You can parse the microseconds:

from datetime import datetime
date_posted = '2014-01-15T01:35:30.314Z'
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%S.%fZ')
Velimir Mlaker
  • 10,664
  • 4
  • 46
  • 58
  • I thought making `datetime` handle `%f` manually if the platform doesn't was only added in 3.1+, but it looks like it was backported to 2.6 as well. Nice. – abarnert Jan 16 '14 at 02:00
12

One option is to let dateutil do the job:

>>> from dateutil import parser
>>> parser.parse('2014-01-15T01:35:30.314Z')
datetime.datetime(2014, 1, 15, 1, 35, 30, 314000, tzinfo=tzutc())
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195