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

作者:songguo 时间:2022-05-22 23:52:46 

本文实例讲述了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,出生日期,年龄
0
投稿

猜你喜欢

  • Swin Transformer图像处理深度学习模型

    2022-01-16 22:32:08
  • Jupyter Notebook打开任意文件夹操作

    2021-04-25 17:11:45
  • Python中使用Inotify监控文件实例

    2021-03-03 14:17:05
  • python机器学习实现决策树

    2021-04-21 07:44:34
  • Python编程实现生成特定范围内不重复多个随机数的2种方法

    2022-05-08 08:49:51
  • python记录程序运行时间的三种方法

    2023-08-25 03:12:19
  • python3 打开外部程序及关闭的示例

    2022-06-16 22:23:15
  • PyCharm 2020.2下配置Anaconda环境的方法步骤

    2022-10-08 14:25:00
  • Windows64x下VScode下载过程

    2021-03-08 20:10:47
  • python time模块用法实例详解

    2023-10-09 18:12:50
  • js实现屏蔽默认快捷键调用自定义事件示例

    2023-09-05 09:28:31
  • Go语言中使用反射的方法

    2023-07-22 22:31:48
  • 基于Python搭建人脸识别考勤系统

    2021-07-08 10:17:42
  • Python调用服务接口的实例

    2021-06-04 18:22:06
  • oracle远程连接服务器数据库图文教程

    2023-07-12 22:22:37
  • Python 'takes exactly 1 argument (2 given)' Python error

    2022-04-19 00:26:05
  • python实现八大排序算法(1)

    2022-05-20 08:17:47
  • pytorch 彩色图像转灰度图像实例

    2023-08-02 17:28:37
  • python图形开发GUI库pyqt5的基本使用方法详解

    2022-07-08 02:31:55
  • PyQT实现菜单中的复制,全选和清空的功能的方法

    2023-08-13 03:09:23
  • asp之家 网络编程 m.aspxhome.com