views:

8921

answers:

5

I need to parse strings like that "2008-09-03T20:56:35.450686Z" into the python's datetime?

I have found only strptime in the python 2.5 std lib, but it not so convinient.

Which is the best way to do that?

Update:

It seems, that python-dateutil works very well. I have found that solution:

d1 = '2008-09-03T20:56:35.450686Z'
d2 = dateutil.parser.parse(d1)
d3 = d2.astimezone(dateutil.tx.tzutc())
+5  A: 

What is the exact error you get? Is it like the following:

>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z

If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.

Try this:

>>> def gt(dt_str):
dt, _, us= dt_str.partition(".")
dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
us= int(us.rstrip("Z"), 10)
return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
>>>
ΤΖΩΤΖΙΟΥ
You can't just strip .Z because it means timezone and can be different. I need to convert date to the UTC timezone.
Alexander Artemenko
A plain datetime object has no concept of timezone. If all your times are ending in "Z", all the datetimes you get are UTC (Zulu time).
ΤΖΩΤΖΙΟΥ
+3  A: 
import re,datetime
s="2008-09-03T20:56:35.450686Z"
d=datetime.datetime(*map(int, re.split('[^\d]', s)[:-1]))
Ted
+8  A: 

Try the iso8601 module; it does exactly this.

There are several other options mentioned on the WorkingWithTime page on the python.org wiki.

Nicholas Riley
+2  A: 

Note in Py3K (and possibly in a new release of 2.6), the %f character catches microseconds.

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%f%Z")

See issue here

sethbc
A: 

what would i do if i have a string like this: Feb 9, 2010 13:03:33.254329000 I can parse it to a nanosecond resolution timestamp with date -d "Feb 9, 2010 13:03:33.254329000" +%s%N and would get: 1265717013254329000 Now I know I can not parse the datetime string with nanosecond resolution in python but i can split it into: Feb 9, 2010 13:03:33 and 254329000 my question would be, which function would parse the first part to a unix timestamp?

xB