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

如何确保MM/DD/YYYY日期格式校验生效并正确写入其他文件?

问题说明

Python开发循环接收用户出生日期输入、校验是否符合MM/DD/YYYY格式的逻辑时,即便输入内容符合格式要求,依然会触发预设的格式错误提示,问题代码如下:

from datetime import datetime
    

a1 = open(to_file,'a')



def confirm_date(d):  
    a_value = False
    value = ""
    
    while a_value == False:
        value = input("Insert BIRTHDDATE in  MM/DD/YYYY format including slashes: ")
    
        try:
            datetime.strptime(d, '%m/%d/%Y')
            a_value = True
            if a_value == True:
              c1 = value
            else:
              c1 != value
    
            except ValueError:
                   print("Error: Date format invalid.")


c = confirm_date(d)



a1.write(c)
print("Thank you! Goodbye!")


a1.close()
问题根因
  • 核心传参错误:datetime.strptime()的待解析参数传入了未定义的函数形参d,而非实际接收到的用户输入内容value,逻辑上从未对用户输入做格式校验,只要形参不符合格式就会持续抛错
  • 语法缩进错误:except代码块未和对应try块保持同级缩进,会直接触发语法报错
  • 逻辑错误:校验通过分支里的c1 != value是无效比较语句,并非赋值操作;且函数未设置return返回值,后续写入文件的逻辑无法拿到有效日期内容
  • 调用错误:调用confirm_date(d)时传入的参数d从未提前定义,且函数内部已经实现了完整的输入接收逻辑,不需要额外传入参数
  • 变量缺失:打开文件时用到的to_file变量未提前定义,会触发名称错误
  • 细节问题:输入提示文案里BIRTHDDATE存在拼写错误,多写了一个字母D;输入提示里MM前多了冗余空格
修复后可运行代码
from datetime import datetime

# 定义待写入的文件路径
to_file = "birth_record.txt"
a1 = open(to_file, 'a', encoding='utf-8')

def confirm_date():
    while True:
        value = input("Insert BIRTHDATE in MM/DD/YYYY format including slashes: ").strip()
        try:
            # 传入用户实际输入的内容做格式校验
            datetime.strptime(value, '%m/%d/%Y')
            return value
        except ValueError:
            print("Error: Date format invalid.")

valid_birth = confirm_date()
a1.write(valid_birth + '\n')
a1.close()
print("Thank you! Goodbye!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:18:42