python-3.x - 在Python中将iso格式的日期时间字符串转换为日期时间对象

标签 python-3.x datetime python-3.6

我在将 iso 格式的日期时间字符串转换为 Python 3.6 中的日期时间对象而不丢失时区信息时遇到问题。 字符串是这样的。

2021-07-04T00:00:00+02:00

我尝试了 datetime.datetime.strptime 方法。但无法设置正确的格式字符串。

datetime.datetime.strptime( "2021-07-04T00:00:00+02:00", "%Y-%m-%dT%H:%M:%S%z")

如果日期时间字符串采用以下格式,则有效:

datetime.strptime("2021-07-04T00:00:00+0200", "%Y-%m-%dT%H:%M:%S%z")

但是在这种格式下,不起作用:

datetime.datetime.strptime( "2021-07-04T00:00:00+02:00", "%Y-%m-%dT%H:%M:%S%z")

我有以下格式的日期时间:

2021-07-04T00:00:00+02:00

最佳答案

对于Python 3.7+,您还可以使用datetime.datetime.fromisoformat()函数 strptime("2021-07-04T00:00:00+02:00", "%Y-%m-%dT%H:%M:%S%z") 可以正常工作。

对于 Python 3.6 及更低版本,时区格式预计为 ±HHMM。因此,您必须在使用 strptime 之前转换字符串(删除最后一个分号)。

例如:

tz_found = t_str.find('+')    
if tz_found!=-1 and t_str.find(':', tz_found)!=-1:
    t_str = t_str[:tz_found+3] + t_str[tz_found+4:tz_found+6]
result = datetime.datetime.strptime( t_str, "%Y-%m-%dT%H:%M:%S%z")

关于python-3.x - 在Python中将iso格式的日期时间字符串转换为日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68435636/

相关文章:

Python:用包含子字符串的单词拆分字符串

UNC 路径的 Python 和 MySQL 转义序列

python - 如何通过python-3.6在网站html中搜索?

python - SSH OverTheWire 脚本

python - 从 pandas df 列的预设字符串列表中拆分字符串

mysql - 每周未结订单数

javascript - 使用 Luxon 格式化 ISO 时间

vb.net DateTime.现在和接下来的 15 分钟

python - 在 python 中以递归方式对文件进行 glob 的干净方法

python - 通过 N 个 for 循环,其中 N 是一个变量