Parsing date with timezone from an email?

2019-01-01 13:30发布

I am trying to retrieve date from an email. At first it's easy:

message = email.parser.Parser().parse(file)
date = message['Date']
print date

and I receive:

'Mon, 16 Nov 2009 13:32:02 +0100'

But I need a nice datetime object, so I use:

datetime.strptime('Mon, 16 Nov 2009 13:32:02 +0100', '%a, %d %b %Y %H:%M:%S %Z')

which raises ValueError, since %Z isn't format for +0100. But I can't find proper format for timezone in the documentation, there is only this %Z for zone. Can someone help me on that?

8条回答
其实,你不懂
2楼-- · 2019-01-01 14:23

For those who want to get the correct local time, here is what I did:

from datetime import datetime
from email.utils import parsedate_to_datetime

mail_time_str = 'Mon, 16 Nov 2009 13:32:02 +0100'

local_time_str = datetime.fromtimestamp(parsedate_to_datetime(mail_time_str).timestamp()).strftime('%Y-%m-%d %H:%M:%S')

print(local_time_str)
查看更多
笑指拈花
3楼-- · 2019-01-01 14:26

ValueError: 'z' is a bad directive in format...

(note: I have to stick to python 2.7 in my case)

I have had a similar problem parsing commit dates from the output of git log --date=iso8601 which actually isn't the ISO8601 format (hence the addition of --date=iso8601-strict in a later version).

Since I am using django I can leverage the utilities there.

https://github.com/django/django/blob/master/django/utils/dateparse.py

>>> from django.utils.dateparse import parse_datetime
>>> parse_datetime('2013-07-23T15:10:59.342107+01:00')
datetime.datetime(2013, 7, 23, 15, 10, 59, 342107, tzinfo=+0100)

Instead of strptime you could use your own regular expression.

查看更多
登录 后发表回答