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

Python中datetime.strptime触发ValueError问题求助

解决datetime模块的ValueError及格式符错误问题

问题1:预约操作的ValueError: unconverted data remains: :31

原因

你输入的日期包含秒数(2023-10-9 8:31:31),但解析时使用的格式字符串%Y-%m-%d %H:%M仅匹配到分钟,导致末尾的:31无法被解析,触发错误。

修复方案

两种可选方案:

  • 方案一:修改输入提示,要求用户仅输入到分钟(格式为yyyy-mm-dd hh:mm),保持原格式字符串不变。
  • 方案二:更新格式字符串以支持秒数匹配,使用%Y-%m-%d %H:%M:%S:
# 原错误代码
date = datetime.datetime.strptime(appnt_date,'%Y-%m-%d %H:%M')
# 修改后代码
date = datetime.datetime.strptime(appnt_date,'%Y-%m-%d %H:%M:%S')

问题2:预约重排代码中的格式符错误

原因

重排代码中误用了格式符%s——Python的datetime格式规范里,秒对应的是大写%S,小写%s代表Unix时间戳(从1970年起的累计秒数),无法匹配时间字符串中的秒数。

修复方案

将格式字符串中的%s替换为%S:

# 原错误代码
date_for_resc = datetime.datetime.strptime(date_resc, '%Y-%m-%d %H:%M:%s')
# 修改后代码
date_for_resc = datetime.datetime.strptime(date_resc, '%Y-%m-%d %H:%M:%S')

附:报错信息及原代码参考

报错输出:

1 . register no.of  doctors 
2 . register no.of patients 
3 . do you want to book appointments ? 
4 . reschedule the appointments ?      
5 . cancel the appointments. 
6 . Exit 
enter your selection : 3 
enter the number of doc : 1 
enter number of patient : 1 
>> 
enter the name of the doctor : knan 
is the doctor free? (y/n) : y 
[]
['y ']
enter the name of the patient : ganesh 
['ganesh ']
lol
enter the date you want to get appointed (yyyy-mm-dd hh:mm): 2023-10-9 8:31:31 
Traceback (most recent call last):
  File "c:\Desktop\vsc\JavaScript\05-Guess-My-Number\starter\doctor.py", line 51, in <module>
    date = datetime.datetime.strptime(appnt_date,'%Y-%m-%d %H:%M')
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\_strptime.py", line 568, in _strptime_datetime        
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: :31 

重排功能原代码:

for k in range(no_of_resc):
                name_resch = input('enter then name of the patient you want to reschedule : ')
                date_resc = input('enter the date you want to reschedule : ')
                date_for_resc = datetime.datetime.strptime(date_resc, '%Y-%m-%d %H:%M:%s')
                print('the appointment is rescheduled for ',name_resch,'and on',date_for_resc)
                resch_pat.append(name_resch)
            print('the appointment is rescheduled for :' , resch_pat)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:35:21