我正在用 Python 编写一个基于 Web 的电子邮件客户端,并且出现了一个问题,即电子邮件的“日期” header 在发送时应表示为哪个时区。
RFC 2822在第 3.3 节中指出:
The date and time-of-day SHOULD express local time.
这对我来说似乎是模棱两可的;问题是谁的本地时间?电子邮件服务器,还是发件人?自然地,我假设发件人(可以在任何时区,并且可以在他们的帐户首选项中更改)。当我查看 Python 的 email.utils.formatdate 时,更加困惑了。功能似乎只提供两种选择:UTC 或本地时间(服务器的)。对我来说似乎没有任何指定备用时区的选项,或者我错过了什么?
使用 time.mktime(senders_tz_aware_now_datetime.timetuple())
将 timeval 传递给 formatdate 会导致 UTC 日期字符串,考虑到 RFC 上面所说的,这感觉是错误的。
那么“日期”应该是哪个时区,是否存在任何标准函数来创建适当的日期字符串?
最佳答案
如果您想遵守 RFC,请传递 localtime=True
,它会返回包含本地时间和正确时区的日期字符串(假设您已正确设置)。
>>> email.utils.formatdate(localtime=True)
'Mon, 07 May 2012 12:09:16 -0700'
如果没有 localtime=True
,您会得到一个表示 UTC 时间的日期字符串:
>>> email.utils.formatdate()
'Mon, 07 May 2012 19:08:55 -0000'
-0000
显然表示 UTC,尽管 RFC 特别建议使用 +0000
。不确定这是否是 email.utils 中的错误。
这是相关的 python 文档:
Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. The default is False meaning UTC is used.
关于python - 电子邮件 "Date"标题应该是发件人的本地时间还是 UTC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10487286/