Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用strtime的日期格式不正确_Python_Datetime - Fatal编程技术网

Python 使用strtime的日期格式不正确

Python 使用strtime的日期格式不正确,python,datetime,Python,Datetime,可能重复: 也许我遗漏了一些东西,但有人能发现为什么没有正确验证吗?最有可能的情况是您的区域设置时区为空,例如,%Z计算结果为' 您可以通过以下方式进行测试: >>> fmt = '%A, %B %d, %Y %I:%M:%S %p %Z' >>> datetime.strptime(datetime.strftime(datetime.now(), fmt), fmt) Traceback (most recent call last): File "

可能重复:


也许我遗漏了一些东西,但有人能发现为什么没有正确验证吗?

最有可能的情况是您的区域设置时区为空,例如,
%Z
计算结果为
'
您可以通过以下方式进行测试:

>>> fmt = '%A, %B %d, %Y %I:%M:%S %p %Z'
>>> datetime.strptime(datetime.strftime(datetime.now(), fmt), fmt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Friday, December 28, 2012 11:34:35 AM ' does not match format '%A, %B %d, %Y %I:%M:%S %p %Z'
>fmt='%A,%B%d,%Y%I:%M:%S%p%Z'
>>>datetime.strtime(datetime.strftime(datetime.now(),fmt),fmt)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py”,第325行,在_strptime中
(数据字符串,格式))
ValueError:时间数据“2012年12月28日星期五上午11:34:35”与格式“%A,%B%d,%Y%I:%M:%S%p%Z”不匹配

您可以省去很多麻烦并使用它

对于eumiro指出的歧义,您可以添加一个
tzinfo
参数:

In [3]: parser.parse('Saturday, December 22, 2012 1:22:24 PM EST',tzinfos={'EST':-5*3600})
Out[3]: datetime.datetime(2012, 12, 22, 13, 22, 24, tzinfo=tzoffset('EST', -18000))
strtime()
函数无法很好地处理
%Z
时区解析。仅支持UTC和GMT,并且当前值为
time.tzname
。见:

%Z
指令的支持基于
tzname
中包含的值以及
daylight
是否为真。因此,它是特定于平台的,但识别UTC和GMT除外,因为UTC和GMT总是已知的(并且被认为是非夏令时时区)

删除输入中的
EST
部分和格式字符串中的
%Z
部分可以使工作正常:

>>> import time
>>> time.strptime('Saturday, December 22, 2012 1:22:24 PM EST', '%A, %B %d, %Y %I:%M:%S %p %Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Saturday, December 22, 2012 1:22:24 PM EST' does not match format '%A, %B %d, %Y %I:%M:%S %p %Z'
>>> time.strptime('Saturday, December 22, 2012 1:22:24 PM', '%A, %B %d, %Y %I:%M:%S %p')
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=22, tm_hour=13, tm_min=22, tm_sec=24, tm_wday=5, tm_yday=357, tm_isdst=-1)
要解析时区不是
time.tzname
GMT
UTC
的字符串,请使用其他日期解析库。具有可正确处理时区的优秀功能:

>>> from dateutil.parser import parse
>>> parse('Saturday, December 22, 2012 1:22:24 PM EST', tzinfos={'EST': -18000})
datetime.datetime(2012, 12, 22, 13, 22, 24, tzinfo=tzoffset(u'EST', -18000))

使用
dateutil.parser.parse()
时,您必须为您的格式提供自己的时区偏移量。

正如@root建议的那样,dateutil.parser是解析日期的可靠方法,但只是为了澄清这里的问题

我刚刚在_strptime.py中看到了代码,似乎支持的时区是

["utc", "gmt", time.tzname[0].lower()]
如果当前区域设置时区支持夏令时,它将附加

time.tzname[0]。将()降低到上面的列表中

因此,在使用strtime时,请确保解析日期的时区支持源时区

这是代码供参考

def __calc_timezone(self):
    # Set self.timezone by using time.tzname.
    # Do not worry about possibility of time.tzname[0] == timetzname[1]
    # and time.daylight; handle that in strptime .
    try:
        time.tzset()
    except AttributeError:
        pass
    no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
    if time.daylight:
        has_saving = frozenset([time.tzname[1].lower()])
    else:
        has_saving = frozenset()
    self.timezone = (no_saving, has_saving)

麻烦还在那里。它忽略了
EST
时区(正确,因为它可以是美国和澳大利亚:)@eumiro-你是对的。我认为您可以在解析时添加
tzinfos
arg来处理它。太好了,我不知道
tzinfos
。日期解析器将仅为上述情况提供正确的datetime对象。但是考虑下面的情况,<代码> > >解析(TunfOS=‘3'-12:24,EST’,Tyffs= {'EST’:-18000 })DATETIME.DATEIME(2011, 12, 13,13, 22, 24,TZnFix= TZOBSET(‘EST’,-18000))> PARSE(“星期六,09-12,11:22:24,EST”,Tyffs= {'EST,--18000 })DATETIME.DATETIME(2011, 9, 12,13, 22, 24,TZnFixTZOffice('EST,-18000))。datetimeobject.date()在这两种情况下都不同。@PSivachandran:这是因为日期不明确。没有13个月,所以第一个例子很明显,格式是以日-月-年的顺序排列的,但是第二个例子可以解释为日-月-年和月-日-年。默认情况下是将日期解析为后者,您可以使用
dayfirst=True
关键字更改日期。@Marijn:Great。谢谢我不知道这个
dayfirst
关键字。没有这个,我完全糊涂了+谢谢你的解释。
>>> from dateutil.parser import parse
>>> parse('Saturday, December 22, 2012 1:22:24 PM EST', tzinfos={'EST': -18000})
datetime.datetime(2012, 12, 22, 13, 22, 24, tzinfo=tzoffset(u'EST', -18000))
["utc", "gmt", time.tzname[0].lower()]
def __calc_timezone(self):
    # Set self.timezone by using time.tzname.
    # Do not worry about possibility of time.tzname[0] == timetzname[1]
    # and time.daylight; handle that in strptime .
    try:
        time.tzset()
    except AttributeError:
        pass
    no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
    if time.daylight:
        has_saving = frozenset([time.tzname[1].lower()])
    else:
        has_saving = frozenset()
    self.timezone = (no_saving, has_saving)