Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strptime() and timezones?

I have a CSV dumpfile from a Blackberry IPD backup, created using IPDDump. The date/time strings in here look something like this (where EST is an Australian time-zone):

Tue Jun 22 07:46:22 EST 2010 

I need to be able to parse this date in Python. At first, I tried to use the strptime() function from datettime.

>>> datetime.datetime.strptime('Tue Jun 22 12:10:20 2010 EST', '%a %b %d %H:%M:%S %Y %Z') 

However, for some reason, the datetime object that comes back doesn't seem to have any tzinfo associated with it.

I did read on this page that apparently datetime.strptime silently discards tzinfo, however, I checked the documentation, and I can't find anything to that effect documented here.

I have been able to get the date parsed using a third-party Python library, dateutil, however I'm still curious as to how I was using the in-built strptime() incorrectly? Is there any way to get strptime() to play nicely with timezones?

like image 825
victorhooi Avatar asked Jul 22 '10 02:07

victorhooi


People also ask

How does Strptime work in Python?

The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.

What is datetime Strptime Python?

strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.


1 Answers

I recommend using python-dateutil. Its parser has been able to parse every date format I've thrown at it so far.

>>> from dateutil import parser >>> parser.parse("Tue Jun 22 07:46:22 EST 2010") datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal()) >>> parser.parse("Fri, 11 Nov 2011 03:18:09 -0400") datetime.datetime(2011, 11, 11, 3, 18, 9, tzinfo=tzoffset(None, -14400)) >>> parser.parse("Sun") datetime.datetime(2011, 12, 18, 0, 0) >>> parser.parse("10-11-08") datetime.datetime(2008, 10, 11, 0, 0) 

and so on. No dealing with strptime() format nonsense... just throw a date at it and it Does The Right Thing.

Update: Oops. I missed in your original question that you mentioned that you used dateutil, sorry about that. But I hope this answer is still useful to other people who stumble across this question when they have date parsing questions and see the utility of that module.

like image 156
Joe Shaw Avatar answered Sep 17 '22 17:09

Joe Shaw