我怎么能从今天的日期和一个人的出生日期找到一个python年龄?出生日期来自Django模型中的DateField。
当前回答
serializers.py
age = serializers.SerializerMethodField('get_age')
class Meta:
model = YourModel
fields = [..,'','birthdate','age',..]
import datetime
def get_age(self, instance):
return datetime.datetime.now().year - instance.birthdate.year
其他回答
如果你想用django模板打印在页面中,那么下面的代码就足够了:
{{ birth_date|timesince }}
不幸的是,您不能只使用时间数据,因为它使用的最大单位是日,闰年将使您的计算无效。因此,让我们找到年数,然后如果最后一年没有满,就按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()称为性能损失是荒谬的,除非在极端特殊的情况下,否则这无关紧要。使用变量的真正原因是数据不一致的风险。
一个比@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对象都适用。
为了便于阅读和理解,稍微修改了Danny的解决方案
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
full_year_passed = (today.month, today.day) < (birth_date.month, birth_date.day)
if not full_year_passed:
age -= 1
return age
最简单的方法是使用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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录