python - 如何仅使用python查找年数

标签 python python-3.x

我想做一个年龄计算器,我想只求年数,请问我提供的代码如何实现?

import datetime

print('birthday')
birthday=datetime.date(1997,7,1)
print(birthday)

print('today')
current=datetime.date.today()
print(current)

age=(current-birthday)//365
print('age')
print(age)

我预计输出应该是 21 年,但实际输出是 21 天加上一些意想不到的信息

最佳答案

它目前假定您要将天数除以 365。因此输出是正确的,只是度量标准不是。尝试明确地将天数除以 365,如下所示:

age = (current-birthday).days // 365
print(age)

另一种方法是使用 dateutil 中的 relativedelta :

from dateutil.relativedelta import relativedelta
birthday = datetime.date(1997, 7, 1)
current = datetime.date.today()
rdelta = relativedelta(current, birthday)
print(rdelta.years)

这样做的好处是您还可以打印月/日 (rdelta.months/rdelta.days)

关于python - 如何仅使用python查找年数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56678462/

相关文章:

python - 仅命名 pandas.read_csv 读取的数据集的最后一列

python - 如何获得keras中的梯度?

python - 打印 numpy 数组作为 python 列表的成员

python - 如何在 python 字典中保持循环以搜索值?

python - Django : Direct assignment to the forward side of a many-to-many set is prohibited. 改为使用 user.set()

python - 使 Python 3 函数接受预设的正确方法是什么?

python - eval(dir()[0]) 在 python 中做什么

python - python3 中的 byte 与 str.encode

python - 如何使嵌套枚举也有值(value)

python - 遗传算法中的矢量化育种方法