Python: 日期转换错误

Python: Date Conversion Error

我正在尝试将字符串转换为日期格式,以便稍后存储到 SQLite 数据库中。下面是我遇到错误的代码行。

date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z')

这是错误:

File "00Basic.py", line 20, in spider
    date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z')   File "C:\Python27\lib\_strptime.py", line 332, in _strptime
    (data_string, format)) ValueError: time data 'Aug 19, 2016 08:13 IST' does not match format '%b %d, %Y %H %M %Z'

问题 1:如何解决此错误?

问题 2:这是准备稍后在 SQLite 中存储日期的正确方法吗?

请注意:编程新手。

问题出在格式的 %Z(时区)部分。 正如 documentation 解释的那样

%Z  Time zone name (empty string if the object is naive).   (empty), UTC, EST, CST

看起来只有 UTC、EST 和 CST 有效。 (或者它只是不识别 IST

为了解决这个问题,您可以使用接受任何 UTC 偏移量的 %z 参数,如下所示:

struct_time = time.strptime("Aug 19, 2016 08:13 +0530", '%b %d, %Y %H:%M %z')

更新:虽然这在 Python +3.2 中工作正常,但在 运行 和 Python2

时引发异常

您可以使用 pytz 进行时区转换,如下所示:

from datetime import datetime
from pytz import timezone

s = "Aug 19, 2016 08:13 IST".replace('IST', '')
print(timezone('Asia/Calcutta').localize(datetime.strptime(s.rstrip(), '%b %d, %Y %H:%M')))
#2016-08-19 08:13:00+05:30
#<class 'datetime.datetime'>

我建议您使用 dateutil 以防您处理字符串的多个时区。