从Python中的字符串中提取日期时间的最佳方法 [英] Best way to extract datetime from string in python
问题描述
我有一个脚本,用于解析电子邮件标题中代表日期和时间的字段。这些字符串的一些示例如下:
I have a script that is parsing out fields within email headers that represent dates and times. Some examples of these strings are as follows:
Fri, 10 Jun 2011 11:04:17 +0200 (CEST)
Tue, 1 Jun 2011 11:04:17 +0200
Wed, 8 Jul 1992 4:23:11 -0200
Wed, 8 Jul 1992 4:23:11 -0200 EST
在遇到某些字符串结尾处的CEST / EST部分之前,我的工作情况还不错使用 datetime.datetime.strptime
像这样:
Before I was confronted with the CEST/EST portions at the ends of some the strings I had things working pretty well just using datetime.datetime.strptime
like this:
msg['date'] = 'Wed, 8 Jul 1992 4:23:11 -0200'
mail_date = datetime.datetime.strptime(msg['date'][:-6], '%a, %d %b %Y %H:%M:%S')
我试图将正则表达式放在一起以匹配字符串的日期部分,但最后不包括时区信息,但是正则表达式出现问题(我无法匹配冒号)。
I tried to put a regex together to match the date portions of the string while excluding the timezone information at the end, but I was having issues with the regex (I couldn't match a colon).
使用正则表达式是解析上面所有示例的最佳方法吗?如果是这样,有人可以共享与这些示例匹配的正则表达式吗?最后,我希望有一个日期时间对象。
Is using a regex the best way to parse all of the examples above? If so, could someone share a regex that would match these examples? In the end I am looking to have a datetime object.
推荐答案
from email import utils
utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200 (CEST)')
utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200')
utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17')
输出为:
(2011, 6, 10, 11, 4, 17, 0, 1, -1, 7200)
(2011, 6, 10, 11, 4, 17, 0, 1, -1, 7200)
(2011, 6, 10, 11, 4, 17, 0, 1, -1, None)
这篇关于从Python中的字符串中提取日期时间的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!