在创建datetime对象时遇到ValueError

时间:2013-10-02 22:15:57

标签: python datetime

我使用以下格式将字符串转换为日期时间对象。

datetime.datetime.strptime(systemTime, '%a %b %d %H:%M:%S %Z %Y')

我为systemTime="Wed Jan 05 06:10:01 GMT 2005"测试了它并且运行正常。 但是当我尝试systemTime="Wed Oct 02 18:01:56 EDT 2013"时,它失败了ValueError

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)
  File "SimpleWebServer.py", line 146, in startUDPServer
    ESTTime = datetime.datetime.strptime(systemTime, '%a %b %d %H:%M:%S %Z %Y')
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Wed Oct 02 18:01:56 EDT 2013' does not match format '%a %b %d %H:%M:%S %Z %Y'

计算机上的语言环境是“en US”。我的格式有什么问题吗?

2 个答案:

答案 0 :(得分:0)

Python不会解析EDT。 UTC虽然有效。

from datetime import datetime
fmt = '%a %b %d %H:%M:%S %Z %Y'
t = "Wed Oct 02 18:01:56 UTC 2013"
print datetime.strptime(t, fmt)

生成有效的日期时间对象

datetime.datetime(2013, 10, 2, 18, 1, 56)

答案 1 :(得分:0)

dateutil包具有用于扩展时区处理的钩子,但不解析EDT - 它解析剩余的日期并将时区留空。您可以使用它并为您的应用程序添加时区。