如何将日期时间字符串转换为sql格式?

问题描述:

是否有任何简短的方法来将此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

你可以简单地切换格式:

>>> 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支持提供的链接。 –

有没有简单的方法来做到这一点。 结账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