>> temp = -6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:54:07 25 4
gpt4 key购买 nike

是否有更短的方法将这个 ISO 8601 兼容的 UTC 时间转换为 SQL DATETIME 格式?

>>> 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'

谢谢!

最佳答案

您可以简单地切换格式:

>>> 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解决方法

关于python - 如何将日期时间字符串转换为 sql 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37210261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com