Default datetime string format with timezone

I am using the default python string date and time format with the JSON web service.

Then I try to compare it with the actual time. And I also use timezone with pytz.utc .

Here is my string date:

 print date 2013-02-26 21:28:37.261134+01:00 

Trying to convert my string to datetime (change for timezone with pytz ):

 if datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f+%Z') < datetime.now(pytz.utc): 

Unfortunately, it does not work.

 ValueError: time data '2013-02-26 21:28:37.261134+01:00' does not match format '%Y-%m-%d %H:%M:%S.%f%Z' 

Can someone tell me the correct syntax for strptime format to use my date?

+6
source share
1 answer

Basically, because the datetime module does not know in advance what time zones are available. It's kind of lame.

I recommend using dateutil . This is a third-party package, but it parses your line out of the door.

 >>> import dateutil.parser >>> dateutil.parser.parse('2013-02-26 21:28:37.261134+01:00') datetime.datetime(2013, 2, 26, 21, 28, 37, 261134, tzinfo=tzoffset(None, 3600)) 
+3
source

All Articles