2016-05-13 190 views
0

是否有任何簡短的方法來將此ISO 8601兼容UTC時間轉換爲SQL DATETIME格式?如何將日期時間字符串轉換爲sql格式?

>>> str = "2016-03-28T20:23:46+0800" 
>>> temp = str.split('T') 
>>> temp[1] = temp[1].rstrip('+') 
>>> temp[1] 
'20:23:46+0800' 
>>> temp[1] = temp[1].split('+')[0] 
>>> result = " ".join(temp) 
>>> result 
'2016-03-28 20:23:46' 

謝謝!

+0

我希望您不打算將此結果格式化或連接到查詢字符串。 –

+0

我打算把它寫成一個元組的屬性,是的,什麼? – paus

+0

http://stackoverflow.com/questions/12281975/convert-timestamps-with-offset-to-datetime-obj-using-strptime – lesingerouge

回答

2

你可以簡單地切換格式:

>>> date_str = "2016-03-28T20:23:46+0800" 
>>> format = '%Y-%m-%dT%H:%M:%S%z' 
>>> new_format = '%Y-%m-%d %H:%M:%S' 
>>> datetime.datetime.strptime(date_str, format).strftime(new_format) 
'2016-03-28 20:23:46' 

這將無法在python 2.x中使用,因爲它不支持%z標誌。請參閱timezone python 2 support以獲得解決方法

+1

在Python 2中,您將遇到%z的問題。檢查了這一點:http://stackoverflow.com/questions/12281975/convert-timestamps-with-offset-to-datetime-obj-using-strptime – lesingerouge

+0

@lesingerouge感謝您的注意。我已經添加了您爲python 2.x支持提供的鏈接。 –

0

有沒有簡單的方法來做到這一點。 結賬this post欲瞭解更多可能解決方案的詳細信息。

如果你正在尋找一個快速的黑客嘗試這個辦法:

st = '2016-03-28T20:23:46+0800' 
st[:19].replace("T", " ") 

或者,如果您需要在日期時間日期:

datetime.datetime.strptime(st[:19], '%Y-%m-%dT%H:%M:%S') 
+0

>>> str '2016-03-28T20:23:46 + 0800' >>> import datetime >>> datetime.datetime.strptime(str,「%Y-%m-%d%H:% (最近呼叫的最後一個): 文件「」,第1行,在中 文件「/usr/lib/python2.7/_strptime.py」,行325,in _strptime (data_string,format)) ValueError:時間數據'2016-03-28T20:23:46 + 0800'與格式不符'%Y-%m-%d%H:%M:%S ' – paus

+0

@paus我的壞,糾正。 – lesingerouge

相關問題