从电子邮件parsingdate和时区?

我正试图从电子邮件中检索date。 起初很简单:

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

我收到:

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

但我需要一个很好的date时间对象,所以我使用:

 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 。 但是我无法在文档中find正确的时区格式,区域只有%Z 。 有人可以帮我吗?

email.utils有一个RFC 2822格式的parsedate()函数,据我所知不被弃用。

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

因此,您仍然需要parsing出时区,并考虑当地的时差:

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

使用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 

你有没有尝试过

 rfc822.parsedate_tz(date) # ? 

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

不过已经不赞成(parsedate_tz现在在email.utils.parsedate_tz )。

但也许这些答案有帮助:

  • 如何在python中用-0400时区stringparsingdate?

  • python时间到第二部分,时区

在Python 3.3+中, email可以为您parsing标题:

 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+开始,如果用%zreplace%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时间的朴素date时间对象,否则它将返回一个具有相应tzinfo集的-0000date时间对象。

在较早的Python版本(2.6+)上parsingrfc 5322date – 时间string :

 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基于datetime文档中的tzinfo子类 :

 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 eg, # 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()) 
 # 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) 

对于python 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))) 

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

(注意:我必须坚持使用python 2.7)

我有一个类似的问题,从git log --date=iso8601的输出parsing提交date,实际上它不是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) 

你可以使用自己的正则expression式来代替strptime