【问题标题】:Check if inputed date is under 18检查输入日期是否小于 18 岁
【发布时间】:2022-11-23 04:52:59
【问题描述】:

如果生日日期未满 18 岁,我如何检查输入的日期?

year=int(input("Year born: "))
month = int(input("Month born: "))
day = int(input("Day born: "))
date = date(year,month,day)

date.today() 可以使用什么代码来检查用户是否未满 18 岁?因为如果我减去 2022- year 它可能不到 17 岁,因为他出生在 12 月

【问题讨论】:

  • 使用 date.date() 函数将输入转换为 date。然后从date.today() 中减去该日期以获得差异。然后检查该差异是否小于 18 年。

标签: python date


【解决方案1】:

您可以按顺序比较所有日期部分:

from datetime import date

def is_under_18(birth):
    now = date.today()
    return (
        now.year - birth.year < 18
        or now.year - birth.year == 18 and (
            now.month < birth.month 
            or now.month == birth.month and now.day <= birth.day
        )
    )

在大多数国家/地区,人们被认为在生日后第二天的年龄为n+1,因此最后一次比较使用&lt;=

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2012-02-24
    • 1970-01-01
    • 2012-01-03
    • 2012-03-02
    • 2022-01-22
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多