問題描述
我正在嘗試轉換格式為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 "<stdin>", line 1, in <module>
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)))
這篇關于使用 strptime 將帶偏移量的時間戳轉換為 datetime obj的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!