我怎么能从今天的日期和一个人的出生日期找到一个python年龄?出生日期来自Django模型中的DateField。
当前回答
一个比@DannyWAdairs稍微优雅一点的解决方案可能是使用.timetuple()方法[Python-doc]:
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - (today.timetuple()[1:3] < born.timetuple()[1:3])
你可以很容易地使用这个来进一步推广它,将其粒度增加到秒,这样,如果它大于或等于当天的秒数,年龄就会增加,例如born是一个datetime对象:
from datetime import datetime
def calculate_age_with_seconds(born):
today = datetime.now()
return today.year - born.year - (today.timetuple()[1:6] < born.timetuple()[1:6])
这对于date或datetime对象都适用。
其他回答
不幸的是,您不能只使用时间数据,因为它使用的最大单位是日,闰年将使您的计算无效。因此,让我们找到年数,然后如果最后一年没有满,就按1调整:
from datetime import date
birth_date = date(1980, 5, 26)
years = date.today().year - birth_date.year
if (datetime.now() - birth_date.replace(year=datetime.now().year)).days >= 0:
age = years
else:
age = years - 1
Upd:
这个解决方案在2月29日开始时确实会导致一个异常。以下是正确的检查:
from datetime import date
birth_date = date(1980, 5, 26)
today = date.today()
years = today.year - birth_date.year
if all((x >= y) for x,y in zip(today.timetuple(), birth_date.timetuple()):
age = years
else:
age = years - 1
Upd2:
将多次调用now()称为性能损失是荒谬的,除非在极端特殊的情况下,否则这无关紧要。使用变量的真正原因是数据不一致的风险。
考虑到int(True)是1,int(False)是0,元组比较从左到右,这可以做得更简单:
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
延伸到丹尼·w·阿代尔回答,得到月也
def calculate_age(b):
t = date.today()
c = ((t.month, t.day) < (b.month, b.day))
c2 = (t.day< b.day)
return t.year - b.year - c,c*12+t.month-b.month-c2
最简单的方法是使用python-dateutil
import datetime
import dateutil
def birthday(date):
# Get the current date
now = datetime.datetime.utcnow()
now = now.date()
# Get the difference between the current date and the birthday
age = dateutil.relativedelta.relativedelta(now, date)
age = age.years
return age
from datetime import date
def age(birth_date):
today = date.today()
y = today.year - birth_date.year
if today.month < birth_date.month or today.month == birth_date.month and today.day < birth_date.day:
y -= 1
return y
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录