Parse rfc3339 date strings in Python?

I have data sets where all dates have the following format:

2012-10-09T19:00:55Z 

I would like to be able to use methods like .weekday on them. How to convert them to the correct format in Python?

+90
python date rfc3339
Apr 24 '14 at 18:46
source share
3 answers

You can use dateutil.parser.parse to parse strings in datetime objects.

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

 from dateutil.parser import parse a = "2012-10-09T19:00:55Z" b = parse(a) print(b.weekday()) # 1 (equal to a Tuesday) 
+154
Apr 24 '14 at 18:50
source share

The answer has already been given here: How to convert an ISO 8601 date and time string to a Python Datetime object?

 d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" ) d.weekday() 
+83
Apr 24 '14 at 18:52
source share

You should take a look at moment which is the Python port of the excellent momentjs js lib.

One of its advantages is the support for ISO 8601 line formats, as well as the general format "%":

 import moment time_string='2012-10-09T19:00:55Z' m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ') print m.format('YYYY-MD H:M') print m.weekday 

Result:

 2012-10-09 19:10 2 
+10
Oct 07 '14 at 12:35 on
source share



All Articles