Python根据年龄计算出生年份

不管通过中文或英文搜索通过年龄来计算出生年份或日期,结果都是教你如何用生日计算年龄的,ITGeeker技术奇客认为应该也有这方面的需求,在此分享自己的代码。

当然反过来计算是无法计算出生日,只能计算出年份,所以不是准确的生日日期。这个代码是在计算出年份后补全月日,把字段存到date格式里,方便日后计算年龄用。

# -*- coding: utf-8 -*-
##############################################################################
#    GeekerMaster奇客大师 www.geekermaster.com
#    Copyright 2019 ITGeeker <alanljj@gmail.com>
##############################################################################
from datetime import datetime, date, timedelta


tday = date.today()
print ('tday: '+str(tday))
#假设年龄40岁
age = 40
birthday_year = tday.year - 40
birthday_mg = str(birthday_year) + '-01-01' #这里的月份和日期是为了补全格式
birthday_full_df = datetime.strptime(birthday_mg, "%Y-%m-%d").date() #格式化为date格式
print ('birthday_full_df: '+str(birthday_full_df))

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

奇客罗方公众号 奇客罗方小程序 奇客罗方客服 ITGeeker Telegram

网站由ITGeeker技术奇客开发并管理;隶属于GeekerCloud奇客罗方智能科技
Site designed and developed by ITGeekerwhich is a sub-website of GeekerCloud
网站地图 | 沪ICP备2021031434号-4