在Python中计算生日,你可以使用以下方法:
从身份证号码中提取出生日期
import datetime
id_number = "" 身份证号码
birthday_str = id_number[6:14] 获取出生日期字符串
birthday = datetime.datetime.strptime(birthday_str, "%Y%m%d") 转换为datetime类型
birthday_format = birthday.strftime("%Y-%m-%d") 格式化为“年-月-日”
print("出生日期为:", birthday_format)
从用户输入中获取出生年月日
a = input("请输入身份证:")
b = a[6:10] 年
c = a[10:12] 月
d = a[12:14] 日
print("您出生于%s年%s月%s日" % (b, c, d))
计算从出生到现在的天数
from datetime import date
today = date.today()
birth_year = int(b)
birth_month = int(c)
birth_day = int(d)
today_year = today.year
today_month = today.month
today_day = today.day
计算今天与生日相差的天数
if today_month > birth_month or (today_month == birth_month and today_day >= birth_day):
age_days = (today_year - birth_year) * 365 + today_day - birth_day
else:
age_days = (today_year - birth_year - 1) * 365 + today_day - birth_day + 1
print("从出生到今天过了%d天" % age_days)
随机生成一个生日
import time
import random
start_birthday = (1970, 10, 10, 0, 0, 0, 0, 0, 0) 设置开始时间元组
end_birthday = (2024, 1, 1, 0, 0, 0, 0, 0, 0) 设置结束时间元组
start = time.mktime(start_birthday) 生成开始时间戳
end = time.mktime(end_birthday) 生成结束时间戳
random_birthday = random.randint(start, end) 随机选择一个时间戳
date_tuple = time.localtime(random_birthday) 时间戳转时间元组
birthday = time.strftime("%Y-%m-%d", date_tuple) 时间元组转换成格式化字符串
print("随机生成的生日是:", birthday)
计算距离下次生日还有多少天
from dateutil.relativedelta import relativedelta
from datetime import datetime
获取今天的日期
today = datetime.today()
获取生日的日期
birthday = datetime(today.year, int(b), int(c), int(d))
如果今天日期大于生日日期,则计算明年的生日
if today > birthday:
birthday = datetime(today.year + 1, int(b), int(c), int(d))
计算距离生日还有多少天
days_until_birthday = (birthday - today).days
print("距离下次生日还有%d天" % days_until_birthday)
以上代码示例展示了如何使用Python进行生日计算的不同方法。你可以根据需要选择合适的方法进行生日的计算