首页 > 解决方案 > python - 如何倒计时直到生日(两个日期之间)

问题描述

我的任务是创建一个程序来检查当前日期是否是你的生日。如果是,请打印“生日快乐!”。如果没有,则输出距离您的生日还有多少天。

我一直在努力完成这项任务,我想我已经让它工作了,但是如何从结果中删除逗号“,”和时间“0:00:00”输出?

我只希望它显示天数和天数。

输入:1989 6 21

期望的输出(在提问的时间/日期!):349 天

非:349 天,0:00:00

希望这很清楚,并提前感谢!

--

到目前为止,我有:

import datetime


today = datetime.date.today()

user_birth_year = int(input("Enter year of birth i.e. 1989: "))
user_birth_month = int(input("Enter month of birth i.e. for June enter 6: "))
user_birth_day = int(input("Enter day of birth i.e. for 21st enter 21: "))

my_birthday = datetime.date(today.year, user_birth_month, user_birth_day)
if my_birthday == today:
    print("Happy Birthday!")
else:
    if my_birthday < today:
        my_birthday = my_birthday.replace(year=today.year + 1)
        days_until_birthday = my_birthday - today
        print(days_until_birthday)

    else:
        days_until_birthday = my_birthday - today
        print(days_until_birthday)

标签: pythondatedatetime

解决方案


这包含在datetime. 如果您只想要天数,请访问该days属性。

else:
    days_until_birthday = my_birthday - today
    print(days_until_birthday.days, "days")

推荐阅读