为什么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

为什么?今天是 2024 年 2 月 29 日。

python datetime
1个回答
2
投票

如果您不指定年份,它将解析为 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.