You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

datetime.strptime报错:时间字符串格式不匹配问题求助

问题:datetime.strptime匹配时间字符串时触发格式不匹配错误

问题重现

执行以下代码:

new_variable = dataset['Time'].units[14:].rstrip()
print ("NEW VARIABLE ", new_variable, type(new_variable), len(new_variable)) 
datetime_variable = datetime.datetime.strptime(new_variable, '%y-%m-%d %H:%M:%S')

得到输出:

NEW VARIABLE  2025-02-07 00:00:00 <class 'str'> 19

但触发错误:

datetime_variable = datetime.strptime(new_variable, '%y-%m-%d %H:%M:%S')
  File "/usr/lib/python3.10/_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/lib/python3.10/_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '2025-02-07 00:00:00' does not match format '%y-%m-%d %H:%M:%S'

问题原因

你误用了年份格式符:

  • 小写%y对应两位数年份(比如25代表2025)
  • 你的时间字符串是四位数年份2025,需要用大写%Y

解决方法

将格式字符串替换为'%Y-%m-%d %H:%M:%S'即可:

datetime_variable = datetime.datetime.strptime(new_variable, '%Y-%m-%d %H:%M:%S')

额外说明

输出显示字符串长度为19,和"2025-02-07 00:00:00"的实际长度完全一致,说明字符串没有隐藏的空白或特殊字符,无需额外处理。

内容的提问来源于stack exchange,提问作者afernandezody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 09:57:06