从电子邮件中解析带有时区的日期?

2022-01-16 00:00:00 python datetime format timezone rfc5322

问题描述

我正在尝试从电子邮件中检索日期.一开始很简单:

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

我收到:

'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')

这会引发 ValueError,因为 %Z 不是 +0100 的格式.但是我在文档中找不到正确的时区格式,只有这个 %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?


解决方案

email.utils 有一个针对 RFC 2822 格式的 parsedate() 函数,它就我知道没有被弃用.

email.utils has a parsedate() function for the RFC 2822 format, which as far as I know is not deprecated.

>>> import email.utils
>>> import time
>>> import datetime
>>> email.utils.parsedate('Mon, 16 Nov 2009 13:32:02 +0100')
(2009, 11, 16, 13, 32, 2, 0, 1, -1)
>>> time.mktime((2009, 11, 16, 13, 32, 2, 0, 1, -1))
1258378322.0
>>> datetime.datetime.fromtimestamp(1258378322.0)
datetime.datetime(2009, 11, 16, 13, 32, 2)

但是请注意,parsedate 方法不考虑时区,并且 time.mktime 总是需要一个本地时间元组,如 这里.

Please note, however, that the parsedate method does not take into account the time zone and time.mktime always expects a local time tuple as mentioned here.

>>> (time.mktime(email.utils.parsedate('Mon, 16 Nov 2009 13:32:02 +0900')) ==
... time.mktime(email.utils.parsedate('Mon, 16 Nov 2009 13:32:02 +0100'))
True

所以你仍然需要解析出时区并考虑本地时差:

So you'll still need to parse out the time zone and take into account the local time difference, too:

>>> REMOTE_TIME_ZONE_OFFSET = +9 * 60 * 60
>>> (time.mktime(email.utils.parsedate('Mon, 16 Nov 2009 13:32:02 +0900')) +
... time.timezone - REMOTE_TIME_ZONE_OFFSET)
1258410122.0

相关文章