python根据出生日期返回年龄的方法
作者:令狐不聪 时间:2023-10-10 23:04:53
本文实例讲述了python根据出生日期返回年龄的方法。分享给大家供大家参考。具体实现方法如下:
def CalculateAge(self, Date):
'''Calculates the age and days until next birthday from the given birth date'''
try:
Date = Date.split('.')
BirthDate = datetime.date(int(Date[0]), int(Date[1]), int(Date[2]))
Today = datetime.date.today()
if (Today.month > BirthDate.month):
NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day)
elif (Today.month < BirthDate.month):
NextYear = datetime.date(Today.year, Today.month + (BirthDate.month - Today.month), BirthDate.day)
elif (Today.month == BirthDate.month):
if (Today.day > BirthDate.day):
NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day)
elif (Today.day < BirthDate.day):
NextYear = datetime.date(Today.year, BirthDate.month, Today.day + (BirthDate.day - Today.day))
elif (Today.day == BirthDate.day):
NextYear = 0
Age = Today.year - BirthDate.year
if NextYear == 0: #if today is the birthday
return '%d, days until %d: %d' % (Age, Age+1, 0)
else:
DaysLeft = NextYear - Today
return '%d, days until %d: %d' % (Age, Age+1, DaysLeft.days)
except:
return 'Wrong date format'
使用方法如下:
print CheckDate('2000.05.05')
希望本文所述对大家的Python程序设计有所帮助。
标签:python,日期,年龄
0
投稿
猜你喜欢
caffe的python接口绘制loss和accuracy曲线
2021-06-15 23:54:21
手写个小组件(组件入门)asp版
2013-06-01 20:29:25
JS中把函数作为另一函数的参数传递方法(总结)
2024-05-05 09:14:39
py-charm延长试用期限实例
2023-03-05 23:00:42
Python实现将16进制字符串转化为ascii字符的方法分析
2023-11-17 12:26:25
解决MYSQL出现Can't create/write to file '/tmp/#sql_5c0_0.MYD'的问题
2024-01-16 07:53:39
php上传大文件设置方法
2023-11-21 19:11:22
深入探寻javascript定时器
2024-04-29 13:36:55
JS中定位 position 的使用实例代码
2024-05-03 15:05:09
破解加密的网页代码方法
2010-03-16 12:35:00
Oracle查询当前的crs/has自启动状态实例教程
2024-01-12 21:24:22
PHP设计模式 注册表模式(多个类的注册)
2023-11-20 06:45:13
Python全景系列之数据类型大盘点
2021-01-10 15:29:19
MySQL5.7.10 安装文档教程详解
2024-01-19 00:37:58
python编程开发之类型转换convert实例分析
2023-03-24 05:48:06
BP神经网络原理及Python实现代码
2022-09-04 21:12:24
python中日志logging模块的性能及多进程详解
2023-08-17 23:19:07
Python用input输入列表的实例代码
2021-09-22 09:33:53
一步一步教你网站同步镜像(转载)
2024-01-21 03:38:11
PyTorch上搭建简单神经网络实现回归和分类的示例
2022-08-02 04:49:42