python - How to parse an ISO 8601-formatted date? -


i need parse rfc 3339 strings "2008-09-03t20:56:35.450686z" python's datetime type.

i have found strptime in python standard library, not convenient.

what best way this?

the python-dateutil package can parse not rfc 3339 datetime strings 1 in question, other iso 8601 date , time strings don't comply rfc 3339 (such ones no utc offset, or ones represent date).

>>> import dateutil.parser >>> dateutil.parser.parse('2008-09-03t20:56:35.450686z') # rfc 3339 format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc()) >>> dateutil.parser.parse('2008-09-03t20:56:35.450686') # iso 8601 extended format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686) >>> dateutil.parser.parse('20080903t205635.450686') # iso 8601 basic format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686) >>> dateutil.parser.parse('20080903') # iso 8601 basic format, date datetime.datetime(2008, 9, 3, 0, 0) 

be warned dateutil.parser intentionally hacky: tries guess format , makes inevitable assumptions (customizable hand only) in ambiguous cases. use if need parse input of unknown format , okay tolerate occasional misreads. (thanks ivan_pozdeev)

the pypi name python-dateutil, not dateutil (thanks code3monk3y):

pip install python-dateutil 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -