你活了多久----快用Python计算一下日期

Posted 鲸落!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了你活了多久----快用Python计算一下日期相关的知识,希望对你有一定的参考价值。

输入你的出生日期和现在的日期或者死亡日期,程序会自动计算你活了多久

# 判断是否为闰年
def runYear(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return 1
    else:
        return 0


# 计算天数
def countDay(currentDay):
    perMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    totalDay = 0
    year = 1970     # 1970年1月1日时间戳,算是电脑出生的日子
    while year < currentDay['year']:
        if runYear(year):
            totalDay = totalDay + 366
        else:
            totalDay = totalDay + 365
        year += 1
    if runYear(currentDay['year']) == 1:
        perMonth[2] += 1
    i = 1
    while i < currentDay['month']:
        totalDay += perMonth[i]
        i += 1
    totalDay += currentDay['day']
    return totalDay


if __name__ == "__main__":
    try:
        print("请输入出生日期年,月,日(例如:2000 1 31):")
        year1, month1, day1 = map(int, input().split())  # 表示连续输入3个int型并分别保存给
        dateBirth = 'year': year1, 'month': month1, 'day': day1
        print("请输入今天的日期年,月,日(例如:2021 11 30):")
        year2, month2, day2 = [int(i) for i in input().split()]
        today = 'year': year2, 'month': month2, 'day': day2
        totalDay1 = countDay(dateBirth)
        totalDay2 = countDay(today)
        print("您从%d年%d月%d日出生到%d年%d月%d日:经历了%d天"
              % (year1, month1, day1, year2, month2, day2, totalDay2 - totalDay1))
    except:
        print("输入格式不对,重新运行程序")

以上是关于你活了多久----快用Python计算一下日期的主要内容,如果未能解决你的问题,请参考以下文章

如何用datedif函数计算起止日期间相隔的时间

猜猜你活了多少年

Python - 按天算年龄

计算活了多少天

iOS之计算上次日期距离现在多久, 如 xx 小时前xx 分钟前等

python日期函数udf-程序分享