python 2 月 29 日被报告为无效日期

问题描述 投票:0回答:1

直到今天我的脚本报告这样的错误:

import datetime

tstr = "02-29 13:34:57.041"
dt = datetime.datetime.strptime(tstr, '%m-%d %H:%M:%S.%f')

错误信息:

  File "/usr/lib/python3.11/_strptime.py", line 579, in _strptime_datetime
    return cls(*args)
           ^^^^^^^^^^
ValueError: day is out of range for month
python datetime
1个回答
0
投票

如果您不指定年份,它将解析为 1900,然后就没有 29 feb 了。

添加 2024 和

%Y
,效果很好

import datetime

tstr = "02-29-2024 13:34:57.041"
dt = datetime.datetime.strptime(tstr, '%m-%d-%Y %H:%M:%S.%f')

print(dt)
#2024-02-29 13:34:57.041000
© www.soinside.com 2019 - 2024. All rights reserved.