Python日期检测

Python编程快速上手——让繁琐工作自动化 第2版》

7.18 实践项目

7.18.1 日期检测

以下为书中的项目介绍:

编写一个正则表达式;可以检测DD/MM/YYYY格式的日期。假设日期的范围是01-31,月份的范围是01~12,年份的范围是1000~2999。请注意,如果日期或月份是一位数字,前面自动加0。
该正则表达式不必检测每个月或闰年的正确日期;它将接受不存在的日期,例如31/02/2020或31/04/2021。然后将这些字符串存储到名为month、day 和year的变量中,并编写其他代码以检测它是否为有效日期。4月、6月、9月和11月有30天,2月有28天,其余月31天。闰年2月有29天。闰年是能被4整除的年,能被100整除的年除外,除非它能被400整除。这种计算使得用大小合理的正则表达式来检测有效日期成为不可能的事,请注意原因。

将以上项目介绍分别发给豆包AI和deepseek V3模型,用一个python脚本编写,以下为得到的回答(均为一遍作答)

豆包AI回答:
import re

# 编写正则表达式
date_pattern = r'(\d{2})/(\d{2})/(\d{4})'

# 测试字符串
test_date = "30/02/3021"

# 匹配日期
match = re.match(date_pattern, test_date)
if match:
    day, month, year = match.groups()
    day = int(day)
    month = int(month)
    year = int(year)

    # 检测是否为有效日期
    is_valid = True
    if month in [4, 6, 9, 11] and day > 30:
        is_valid = False
    elif month == 2:
        is_leap_year = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
        if is_leap_year and day > 29:
            is_valid = False
        elif not is_leap_year and day > 28:
            is_valid = False
    elif month not in range(1, 13) or day > 31:
        is_valid = False

    if is_valid:
        print(f"{test_date} 是有效日期")
    else:
        print(f"{test_date} 不是有效日期")
else:
    print(f"{test_date} 不是有效的日期格式")

运行结果:

基本功能可以实现

28/02/2015 是有效日期
30/02/2015 不是有效日期

 但无视了"年份的范围是1000~2999"这一规则

28/02/3021 是有效日期
deepseek V3模型回答:
import re

# 正则表达式匹配 DD/MM/YYYY 格式的日期
date_pattern = re.compile(r'^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/(1[0-9]{3}|2[0-9]{3})$')


def extract_date(date_str):
    """
    从字符串中提取 day, month, year
    """
    match = date_pattern.match(date_str)
    if match:
        day, month, year = match.groups()
        return int(day), int(month), int(year)
    else:
        return None


def is_leap_year(year):
    """
    判断是否为闰年
    """
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    return False


def is_valid_date(day, month, year):
    """
    检查日期是否有效
    """
    # 检查月份和日期的有效性
    if month in {4, 6, 9, 11}:  # 4月、6月、9月、11月有30天
        if day > 30:
            return False
    elif month == 2:  # 2月
        if is_leap_year(year):  # 闰年2月有29天
            if day > 29:
                return False
        else:  # 非闰年2月有28天
            if day > 28:
                return False
    else:  # 其他月份有31天
        if day > 31:
            return False
    return True


def main():
    # 输入日期
    date_str = input("请输入日期 (DD/MM/YYYY): ")

    # 提取日期
    date = extract_date(date_str)
    if date:
        day, month, year = date
        print(f"提取的日期: Day={day}, Month={month}, Year={year}")

        # 检查日期是否有效
        if is_valid_date(day, month, year):
            print(f"{date_str} 是一个有效的日期。")
        else:
            print(f"{date_str} 是一个无效的日期。")
    else:
        print("日期格式无效,请使用 DD/MM/YYYY 格式。")


if __name__ == "__main__":
    main()

运行结果:

基本功能可以实现

请输入日期 (DD/MM/YYYY): 28/02/2015
提取的日期: Day=28, Month=2, Year=2015
28/02/2015 是一个有效的日期。
请输入日期 (DD/MM/YYYY): 30/02/2015
提取的日期: Day=30, Month=2, Year=2015
30/02/2015 是一个无效的日期。

且覆盖"年份的范围是1000~2999"这一规则,但提示未做额外处理(未继续问答求索)

请输入日期 (DD/MM/YYYY): 28/02/3021
日期格式无效,请使用 DD/MM/YYYY 格式。
总结:

本项目主要考验对正则表达式的应用,以及对日期判断的相关方法。本项目建议采用deepseek的回答作为参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值