40

I'm using the Paypal API and I get back a timestamp in the following format. I try to parse this to a datetime object using strptime, but I get the following error:

(Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ')
*** error: redefinition of group name 'M' as group 5; was group 2

Also, as this format is supposed to be quite a standard format isn't there a function available for this?

EDIT:

Ok seems to be a typo. First %M should be %m

4 Answers 4

71

The parser from dateutil is your friend.

You'll have to pip install dateutil but you've save bags and bags of date conversion code:

pip install python-dateutil

You can use it like this.

from dateutil import parser
ds = '2012-03-01T10:00:00Z' # or any date sting of differing formats.
date = parser.parse(ds)

You'll find you can deal with almost any date string formats with this parser and you'll get a nice standard python date back

Sign up to request clarification or add additional context in comments.

1 Comment

Please up vote and change this to your fav answer then please @arno_v
36

Looks like you're mixing %M (minute) and %m (month).

Comments

11

The problem is that you use %M twice. Use %m for the months:

>>> datetime.strptime('2012-03-01T10:00:00Z','%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2012, 3, 1, 10, 0)

2 Comments

Why should I use time? Makes sense to use datetime here right? Since this is both a date and a time.
@arno_v: I see, you're using the class method datetime.strptime. Sorry about that.
3

You have a typo. %M is used twice. You meant to use %m for the month. From the docs:

%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.