Parsing date with timezone from an email?(从电子邮件中解析带有时区的日期?)
问题描述
我正在尝试从电子邮件中检索日期.一开始很简单:
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
这篇关于从电子邮件中解析带有时区的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从电子邮件中解析带有时区的日期?
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
