无法在python中将字符串转换为日期时间

2024-04-19 23:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试下面的代码,虽然格式似乎是正确的,但似乎抛出了一个错误:

from datetime import datetime

utc_time1 = datetime.strptime("2019-07-12T05:49:55:2771249Z", "%Y-%m-%dT%H:%M:%S:%fZ")
print(utc_time1)

utc_time2 = datetime.strptime("2019-07-12T05:49:55.2771249Z", "%Y-%m-%dT%H:%M:%S.%fZ")
print(utc_time2)

我得到以下错误:

Traceback (most recent call last):
  File "C:/Users/bhatak/PycharmProjects/untitled/test.py", line 3, in <module>
    utc_time1 = datetime.strptime("2019-07-12T05:49:55:2771249Z", "%Y-%m-%dT%H:%M:%S:%fZ")
  File "C:\Users\bhatak\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\bhatak\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data '2019-07-12T05:49:55:2771249Z' does not match format '%Y-%m-%dT%H:%M:%S:%fZ'

Tags: inpyformatdatadatetime错误lineusers
1条回答
网友
1楼 · 发布于 2024-04-19 23:26:18

来自文档https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).

毫秒有7位数,%f表达式最多有6位数。如果你删除最后一个你将不会有任何问题。你知道吗

277124而不是2771249。你知道吗

相关问题 更多 >