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

Python日期验证作业求助:已完成有效性校验,需实现星期输出功能

嘿,你已经搞定日期有效性校验的部分,真不错!要实现输出星期几的功能其实很简单,咱们用Python的datetime模块就能轻松搞定,我来给你补全代码并解释清楚~

解决方案

咱们可以利用datetime模块的内置能力,既可以完成更精准的日期有效性校验(自动处理闰年、不同月份天数差异等细节),又能轻松获取对应的星期几。

完整示例代码

import datetime

print("This program will check if a date is correct and output what day of the week it was.")

# 获取输入并转换为整数
try:
    day = int(input("Please input the day: "))
    month = int(input("Please input the month: "))
    year = int(input("Please input the year: "))
except ValueError:
    print("Error: Day, month, and year must be valid integers!")
    exit()

# 验证日期有效性并获取星期几
try:
    # 创建日期对象,无效日期会自动抛出ValueError
    target_date = datetime.date(year, month, day)
except ValueError as err:
    print(f"Oops, that's an invalid date: {err}")
else:
    # 获取星期几的两种常用方式
    # 1. 英文星期(完整名称/缩写)
    weekday_full = target_date.strftime("%A")
    weekday_short = target_date.strftime("%a")
    
    # 2. 中文星期(如果需要的话)
    chinese_weekdays = {
        0: "星期一",
        1: "星期二",
        2: "星期三",
        3: "星期四",
        4: "星期五",
        5: "星期六",
        6: "星期日"
    }
    weekday_chinese = chinese_weekdays[target_date.weekday()]
    
    # 输出结果
    print(f"Great! The date {target_date} is valid.")
    print(f"It was a {weekday_full} ({weekday_short}).")
    print(f"对应的中文星期是:{weekday_chinese}")

关键知识点解释

  • 日期有效性校验:datetime.date(year, month, day)会自动验证日期合法性,比如2月30日、13月这类无效日期会直接抛出ValueError,比手动判断月份、天数范围要靠谱得多,还能自动处理闰年的2月天数。
  • 获取星期几:
    • strftime("%A")返回英文完整星期名称(如"Friday"),%a返回缩写(如"Fri");
    • weekday()方法返回0-6的整数,对应周一到周日,搭配自定义字典就能转换成中文星期;
    • 如果习惯ISO标准(1=周一,7=周日),可以用isoweekday()方法,调整字典对应关系即可。

如果你已经有自己的日期校验逻辑,只需要在确认日期有效后,创建datetime.date对象,再调用上面的方法获取星期几就好啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:39:01