python根据出生日期获得年龄的方法

yipeiwu_com5年前Python基础

本文实例讲述了python根据出生日期获得年龄的方法。分享给大家供大家参考。具体如下:

这段代码可以根据用户的出生日期获得其年龄,born参数为date类型

def calculate_age(born):
 today = date.today()
 try:
  birthday = born.replace(year=today.year)
 except ValueError:
# raised when birth date is February 29 
# and the current year is not a leap year
  birthday = born.replace(year=today.year, day=born.day-1)
 if birthday > today:
  return today.year - born.year - 1
 else:
  return today.year - born.year

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python strip() 函数和 split() 函数的详解及实例

 python strip() 函数和 split() 函数的详解及实例 一直以来都分不清楚strip和split的功能,实际上strip是删除的意思;而split则是分割的意...

Python 'takes exactly 1 argument (2 given)' Python error

Python初学,定义urlConfig 接收参数,正常传递参数时,出现,多给了一个参数的错误问题, 定义class的函数之后,在调用的时候出现“'takes exactly 1 arg...

python3使用flask编写注册post接口的方法

使用python3的Flask库写了一个接口,封装了很多东西,仅供参考即可! 代码如下: #!/usr/bin/python3 # -*- coding: utf-8 -*- im...

python pandas 时间日期的处理实现

python pandas 时间日期的处理实现

摘要在上一篇文章,时间日期处理的入门里面,我们简单介绍了一下载pandas里对时间日期的简单操作。下面将补充一些常用方法。 时间日期的比较 假设我们有数据集df如下 在对时间日期...

Python压缩解压缩zip文件及破解zip文件密码的方法

Python压缩解压缩zip文件及破解zip文件密码的方法

python 的 zipfile 提供了非常便捷的方法来压缩和解压 zip 文件。 例如,在py脚本所在目录中,有如下文件: readability/readability.js r...