Parse rfc3339 date strings in Python?

Spearfisher picture Spearfisher · Apr 24, 2014 · Viewed 128.3k times · Source

I have a datasets where all the dates have the following format:

2012-10-09T19:00:55Z

I'd like to be able to be able to use methods like .weekday on them. How do I convert them to the proper format in Python?

Answer

Ffisegydd picture Ffisegydd · Apr 24, 2014

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)