9

I'm using the default python datetime string format with a JSON webservice.

Then, I'm trying to compare it with an actual datetime. And I'm also using 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 into a datetime (edit for timezone with pytz):

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

Unfortunately, it doesn't 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 anyone tell me the correct syntax for the strptime format, to use my date ?

Arthur
  • 3,717
  • 7
  • 28
  • 44
  • You cannot compare the aware timezone with `datetime.now()` though, you'll have to give the latter a timezone too. See [How to make an unaware datetime timezone aware in python](http://stackoverflow.com/q/7065164) – Martijn Pieters Feb 27 '13 at 20:06
  • You're right about the duplicate, thank you. Google gave me nothing... For the timezone, I was actually using `datetime.now(pytz.utc)` in my code. Sorry for the misleading.... – Arthur Feb 27 '13 at 20:07

1 Answers1

7

Basically that's because the datetime module doesn't know ahead of time about what the available timezones are. It's kind of lame.

I recommend using dateutil. It's a third party package, but it parses your string out 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))
Ken Kinder
  • 12,654
  • 6
  • 50
  • 70