将字符串转换为datetime对象 [英] Converting string to datetime object
问题描述
我正在尝试将字符串转换为datetime对象。
从新闻提要获取的字符串格式如下:
Thu,16 Oct 2014 01:16:17 EDT
我尝试使用datetime.strptime()来转换它。
ie,
datetime.strptime('Thu,16 Oct 2014 01:16:17 EDT','% a,%d%b%Y%H:%M:%S%Z')
收到以下错误:
追溯(最近的最近通话):
File,第1行,
datetime.strptime('Thu,16 Oct 2014 01:16:17 EDT','%a,%d%b%Y%H:%M:%S%Z')
文件C:\Anaconda\lib_strptime.py,第325行,_strptime
(data_string,格式))
ValueError:时间数据'星期四,16十一月2014 01:16:17 EDT'不匹配
格式'%a,%d%b%Y%H:%M:%S%Z'
但是,如果我尝试没有EDT的字符串,它的工作。
ie,
datetime.strptime('Thu,16 Oct 2014 01:16:17','%a ,%d%b%Y%H:%M:%S')
有谁知道解析EDT部分?
解析 RFC 2822格式,您可以使用电子邮件
包:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $
$ b timestamp = mktime_tz(parsedate_tz Thu,16 Oct 2014 01:16:17 EDT))
# - > 1413436577
utc_dt = datetime(1970,1,1)+ timedelta(seconds = timestamp)
# - > datetime.datetime(2014,10,16,5,16,17)
注意:$ $ c> parsedate_tz()假定EDT对应于 -0400
UTC偏移量,但在澳大利亚可能不正确,其中EDT为 +1100
(在这种情况下,AEDT由 pytz
使用),即时区缩写可能不明确。请参阅使用Python中的时区缩写名称解析日期/时间字符串?
相关Python错误: strptime中的%Z与EST和其他人不匹配。
I was trying to convert a string to a datetime object. The string I got from a news feed is in the following format: "Thu, 16 Oct 2014 01:16:17 EDT"
I tried using datetime.strptime() to convert it. i.e.,
datetime.strptime('Thu, 16 Oct 2014 01:16:17 EDT','%a, %d %b %Y %H:%M:%S %Z')
And got the following error:
Traceback (most recent call last):
File "", line 1, in datetime.strptime('Thu, 16 Oct 2014 01:16:17 EDT','%a, %d %b %Y %H:%M:%S %Z')
File "C:\Anaconda\lib_strptime.py", line 325, in _strptime (data_string, format))
ValueError: time data 'Thu, 16 Oct 2014 01:16:17 EDT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
However, if I tried the string without "EDT", it worked. i.e.,
datetime.strptime('Thu, 16 Oct 2014 01:16:17','%a, %d %b %Y %H:%M:%S')
Does anyone know how to parse that "EDT" part?
To parse the date in RFC 2822 format, you could use email
package:
from datetime import datetime, timedelta
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz("Thu, 16 Oct 2014 01:16:17 EDT"))
# -> 1413436577
utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
# -> datetime.datetime(2014, 10, 16, 5, 16, 17)
Note: parsedate_tz()
assumes that EDT corresponds to -0400
UTC offset but it might be incorrect in Australia where EDT is +1100
(AEDT is used by pytz
in this case) i.e., a timezone abbreviation may be ambiguous. See Parsing date/time string with timezone abbreviated name in Python?
Related Python bug: %Z in strptime doesn't match EST and others.
这篇关于将字符串转换为datetime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!