Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default datetime string format with timezone [duplicate]

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 ?

like image 930
Arthur Avatar asked Feb 27 '13 19:02

Arthur


1 Answers

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))
like image 93
Ken Kinder Avatar answered Oct 06 '22 13:10

Ken Kinder