38

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

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

我收到:

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

但我需要一个不错的日期时间对象,所以我使用:

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

这引起了ValueError, since %Z isn't format for +0100. 但是我在文档中找不到正确的时区格式,只有这个%Z用于时区。有人可以帮我吗?

4

8 回答 8

38

email.utils具有parsedate()RFC 2822 格式的功能,据我所知并没有被弃用。

>>> 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总是需要一个本地时间元组,如此所述。

>>> (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

因此,您仍然需要解析时区并考虑本地时差:

>>> 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
于 2009-11-24T15:42:23.283 回答
36

使用email.utils.parsedate_tz(date)

msg=email.message_from_file(open(file_name))
date=None
date_str=msg.get('date')
if date_str:
    date_tuple=email.utils.parsedate_tz(date_str)
    if date_tuple:
        date=datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
if date:
    ... # valid date found
于 2011-12-01T10:22:20.863 回答
12

对于 python 3.3+,您可以使用parsedate_to_datetime函数:

>>> from email.utils import parsedate_to_datetime
>>> parsedate_to_datetime('Mon, 16 Nov 2009 13:32:02 +0100')
...
datetime.datetime(2009, 11, 16, 13, 32, 2, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))

官方文档:

format_datetime() 的倒数。执行与 parsedate() 相同的功能,但成功时返回日期时间。如果输入日期的时区为 -0000,则日期时间将是一个天真的日期时间,如果日期符合 RFC,它将表示 UTC 时间,但不指示消息的实际源时区日期到来从。如果输入日期具有任何其他有效的时区偏移量,则日期时间将是具有相应时区 tzinfo 的感知日期时间。3.3 版中的新功能。

于 2017-08-17T19:01:03.660 回答
10

在 Python 3.3+ 中,emailmessage 可以为您解析标头:

import email
import email.policy

headers = email.message_from_file(file, policy=email.policy.default)
print(headers.get('date').datetime)
# -> 2009-11-16 13:32:02+01:00

从 Python 3.2+ 开始,如果您替换%Z%z

>>> from datetime import datetime
>>> datetime.strptime("Mon, 16 Nov 2009 13:32:02 +0100", 
...                   "%a, %d %b %Y %H:%M:%S %z")
datetime.datetime(2009, 11, 16, 13, 32, 2,
                  tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))

或使用email包(Python 3.3+):

>>> from email.utils import parsedate_to_datetime
>>> parsedate_to_datetime("Mon, 16 Nov 2009 13:32:02 +0100")
datetime.datetime(2009, 11, 16, 13, 32, 2,
                  tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))

如果将 UTC 偏移量指定为,-0000则它返回一个表示 UTC 时间的原始日期时间对象,否则它返回一个具有相应tzinfo集合的感知日期时间对象。

要在早期 Python 版本(2.6+)上解析rfc 5322 日期时间字符串:

from calendar import timegm
from datetime import datetime, timedelta, tzinfo
from email.utils import parsedate_tz

ZERO = timedelta(0)
time_string = 'Mon, 16 Nov 2009 13:32:02 +0100'
tt = parsedate_tz(time_string)
#NOTE: mktime_tz is broken on Python < 2.7.4,
#  see https://bugs.python.org/issue21267
timestamp = timegm(tt) - tt[9] # local time - utc offset == utc time
naive_utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
aware_utc_dt = naive_utc_dt.replace(tzinfo=FixedOffset(ZERO, 'UTC'))
aware_dt = aware_utc_dt.astimezone(FixedOffset(timedelta(seconds=tt[9])))
print(aware_utc_dt)
print(aware_dt)
# -> 2009-11-16 12:32:02+00:00
# -> 2009-11-16 13:32:02+01:00

其中FixedOffset基于文档中的tzinfo子类datetime

class FixedOffset(tzinfo):
    """Fixed UTC offset: `time = utc_time + utc_offset`."""
    def __init__(self, offset, name=None):
        self.__offset = offset
        if name is None:
            seconds = abs(offset).seconds
            assert abs(offset).days == 0
            hours, seconds = divmod(seconds, 3600)
            if offset < ZERO:
                hours = -hours
            minutes, seconds = divmod(seconds, 60)
            assert seconds == 0
            #NOTE: the last part is to remind about deprecated POSIX
            #  GMT+h timezones that have the opposite sign in the
            #  name; the corresponding numeric value is not used e.g.,
            #  no minutes
            self.__name = '<%+03d%02d>GMT%+d' % (hours, minutes, -hours)
        else:
            self.__name = name
    def utcoffset(self, dt=None):
        return self.__offset
    def tzname(self, dt=None):
        return self.__name
    def dst(self, dt=None):
        return ZERO
    def __repr__(self):
        return 'FixedOffset(%r, %r)' % (self.utcoffset(), self.tzname())
于 2014-04-16T18:14:18.477 回答
2

你有没有尝试过

rfc822.parsedate_tz(date) # ?

更多关于 RFC822,http: //docs.python.org/library/rfc822.html

不过,它已被弃用(parsedate_tz 现在位于email.utils.parsedate_tz)。

但也许这些答案会有所帮助:

于 2009-11-24T15:32:21.620 回答
1
# Parses Nginx' format of "01/Jan/1999:13:59:59 +0400"
# Unfortunately, strptime doesn't support %z for the UTC offset (despite what
# the docs actually say), hence the need # for this function.
def parseDate(dateStr):
    date = datetime.datetime.strptime(dateStr[:-6], "%d/%b/%Y:%H:%M:%S")
    offsetDir = dateStr[-5]
    offsetHours = int(dateStr[-4:-2])
    offsetMins = int(dateStr[-2:])
    if offsetDir == "-":
        offsetHours = -offsetHours
        offsetMins = -offsetMins
    return date + datetime.timedelta(hours=offsetHours, minutes=offsetMins)
于 2016-06-14T23:04:26.177 回答
0

对于那些想要获得正确的当地时间的人,这是我所做的:

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)
于 2018-06-16T04:14:25.180 回答
-1

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

(注意:就我而言,我必须坚持使用 python 2.7)

我在解析提交日期时遇到了类似的问题,其输出git log --date=iso8601实际上不是 ISO8601 格式(因此--date=iso8601-strict在更高版本中添加了)。

由于我正在使用django,我可以利用那里的实用程序。

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)

而不是strptime你可以使用你自己的正则表达式。

于 2015-03-16T17:04:07.190 回答