You are not logged in.
Pages: 1
I wrote a python script to get my e-mails via IMAP, works great except, time data isn't consistently formatted. I have a little bit of code to iterate over a list of formats to try, but chokes on this string
Thu, 29 Nov 2012 10:36:34 -0600 (CST)
this format should work. Shouldn't it?
"%a, %d %b %Y %H:%M:%S %z (%Z)"
Here is what interactive promt gives me
>>> DateNow = datetime.datetime.strptime("Thu, 29 Nov 2012 10:36:34 -0600 (CST)", "%a, %d %b %Y %H:%M:%S %z (%Z)")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.3/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.3/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data 'Thu, 29 Nov 2012 10:36:34 -0600 (CST)' does not match format '%a, %d %b %Y %H:%M:%S %z (%Z)'
>>>
What am I missing?
Offline
AFAIK the standard python library is a bit lacking on timezone handling; if I recall correctly the strptime does not even support %Z or %z. strftime will return '' for %z if timezone information is missing from the original object. You will probably need to use an external module such as dateutil which can handle timezones properly. For example
>>> from dateutil.parser import parser
>>> p = parser()
>>> p.parse("Thu, 29 Nov 2012 10:36:34 -0600 (CST)")
datetime.datetime(2012, 11, 29, 10, 36, 34, tzinfo=tzoffset('CST', -21600))
Handling of timezone conversions is quite a daunting task. I think dateutil is the easier way to get going, no need to reinvent the wheel.
Offline
Removing the time zone name seems works:
datetime.datetime.strptime("Thu, 29 Nov 2012 10:36:34 -0600 (CST)"[:-6], "%a, %d %b %Y %H:%M:%S %z")
Last edited by N30N (2012-11-29 22:16:29)
Offline
Thanks for the feedback. After experimenting I've concluded that the CST bit is unknown to srptime as I change it to say PST all is well(Other than the wrong time zone). I'll look at using dateutil. I don't need the timezone data, I just wanted a more standard look for the dates.
As far as using the time module I believe it suffers the same problem as I believe they share a codebase
Offline
[offtopic]
Handling of timezone conversions is quite a daunting task. I think dateutil is the easier way to get going, no need to reinvent the wheel.
If you don't mind using an external library you may try pytz
http://pypi.python.org/pypi/pytz/
[\offtopic]
Offline
Have you seen email.utils.parsedate() and friends?
Offline
Pages: 1