【问题标题】:Python how to convert string with special character into datetimePython如何将带有特殊字符的字符串转换为日期时间
【发布时间】:2021-12-24 08:55:41
【问题描述】:

尝试将字符串转换为日期时间:

from datetime import datetime

date_string = "2021-07-07T02:27:00Z"

datetime.strptime('2021-07-07T02:27:00Z', '%Y-%M-%d %H:%M:%S')


Error:
error: redefinition of group name 'M' as group 5; was group 2 at position 107

然后我试过了:

datetime.fromisoformat(date_string)

还是不行。

有朋友可以帮忙吗?

【问题讨论】:

标签: python python-3.x datetime datetime-format python-datetime


【解决方案1】:

您的格式字符串不正确。


>>> datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 7, 7, 2, 27, tzinfo=datetime.timezone.utc)

【讨论】:

  • Z (= UTC) 不应通过在解析指令中使用文字 Z 来忽略。为什么?因为它为您提供了简单的日期时间,Python 将其视为 本地时间,这很可能是 not UTC。您可以在指令中使用%z。另请参阅我链接的欺骗问题。
  • @MrFuppes 已编辑,谢谢!
猜你喜欢
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 2015-02-20
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
相关资源
最近更新 更多