问题描述
我正在尝试转换格式为2012-07-24t23:14:29-07:00"的时间戳使用 strptime 方法到 python 中的日期时间对象.问题在于最后的时间偏移(-07:00).没有偏移我可以成功
i am trying to convert time-stamps of the format "2012-07-24t23:14:29-07:00" to datetime objects in python using strptime method. the problem is with the time offset at the end(-07:00). without the offset i can successfully do
time_str = "2012-07-24t23:14:29" time_obj=datetime.datetime.strptime(time_str,'%y-%m-%dt%h:%m:%s')
但是我尝试了偏移量
time_str = "2012-07-24t23:14:29-07:00" time_obj=datetime.datetime.strptime(time_str,'%y-%m-%dt%h:%m:%s-%z').
但它给出了一个值错误,说z"是一个错误的指令.
but it gives a value error saying "z" is a bad directive.
有什么解决办法吗?
推荐答案
python 2 strptime() 函数确实不支持 %z 格式的时区(因为底层 time.strptime() 函数不支持).你有两个选择:
the python 2 strptime() function indeed does not support the %z format for timezones (because the underlying time.strptime() function doesn't support it). you have two options:
使用strptime解析时忽略时区:
time_obj = datetime.datetime.strptime(time_str[:19], '%y-%m-%dt%h:%m:%s')
使用 dateutil 模块,它是解析函数确实处理时区:
from dateutil.parser import parse time_obj = parse(time_str)
命令提示符下的快速演示:
quick demo on the command prompt:
>>> from dateutil.parser import parse >>> parse("2012-07-24t23:14:29-07:00") datetime.datetime(2012, 7, 24, 23, 14, 29, tzinfo=tzoffset(none, -25200))
您还可以升级到 python 3.2 或更高版本,其中的时区支持已经改进到 %z 可以工作,前提是您从输入,以及 %z 之前的 -:
you could also upgrade to python 3.2 or newer, where timezone support has been improved to the point that %z would work, provided you remove the last : from the input, and the - from before the %z:
>>> import datetime >>> time_str = "2012-07-24t23:14:29-07:00" >>> datetime.datetime.strptime(time_str, '%y-%m-%dt%h:%m:%s%z') traceback (most recent call last): file "", line 1, in file "/users/mj/development/library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 500, in _strptime_datetime tt, fraction = _strptime(data_string, format) file "/users/mj/development/library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 337, in _strptime (data_string, format)) valueerror: time data '2012-07-24t23:14:29-07:00' does not match format '%y-%m-%dt%h:%m:%s%z' >>> ''.join(time_str.rsplit(':', 1)) '2012-07-24t23:14:29-0700' >>> datetime.datetime.strptime(''.join(time_str.rsplit(':', 1)), '%y-%m-%dt%h:%m:%s%z') datetime.datetime(2012, 7, 24, 23, 14, 29, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))