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程序设计有所帮助。

相关文章

Flask入门教程实例:搭建一个静态博客

Flask入门教程实例:搭建一个静态博客

现在流行的静态博客/网站生成工具有很多,比如 Jekyll, Pelican, Middleman, Hyde 等等,StaticGen 列出了目前最流行的一些静态网站生成工具。 我们的...

Python递归遍历列表及输出的实现方法

本文实例讲述了Python递归遍历列表及输出的实现方法。分享给大家供大家参考。具体实现方法如下: def dp(s): if isinstance(s,(int,str)):...

Python3.7中安装openCV库的方法

1.首先自己直接在cmd中输入 pip3 install openCV是不可行的,即需要自己下载安装包本地安装 2.openCV库 下载地址http://www.lfd.uci.edu/...

Python3.6+Django2.0以上 xadmin站点的配置和使用教程图解

Python3.6+Django2.0以上 xadmin站点的配置和使用教程图解

1. xadmin的介绍 django自带的admin站点虽然功能强大,但是界面不是很好看。而xadmin界面好看,功能更强大,并完全支持Bootstrap主题模板。xadmin内置了丰...

Python中time模块和datetime模块的用法示例

time模块方法: time.time():获取当前时间的时间戳 time.localtime():接受一个时间戳,并把它转化为一个当前时间的元组。不给参数的话就会默认将time.tim...