娱乐一下,用python算一下你的八字

#通过自己的出生年、月、日、时来计算八字哦

一、使用到的包
pip install lunarcalendar
二、源代码

废话不多说,直接上代码,只需要修改对应的年、月、日、时即可:

from lunarcalendar import Converter, Solar, Lunar

# 天干表
heavenly_stems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸']
# 地支表
earthly_branches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']

# 时辰表(每个时辰两个小时)
hours_branches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']

def get_heavenly_stem_and_earthly_branch(offset):
    """根据偏移量计算天干地支"""
    heavenly_stem = heavenly_stems[offset % 10]
    earthly_branch = earthly_branches[offset % 12]
    return heavenly_stem + earthly_branch

def calculate_bazi(year, month, day, hour):
    # 将公历转换为农历
    solar = Solar(year, month, day)
    lunar = Converter.Solar2Lunar(solar)
    
    # 计算年柱
    year_offset = lunar.year - 4
    year_pillar = get_heavenly_stem_and_earthly_branch(year_offset)

    # 计算月柱
    month_offset = (lunar.month - 1) + 12 * ((year_offset % 5) + 1)
    month_pillar = get_heavenly_stem_and_earthly_branch(month_offset)

    # 计算日柱
    # 这里日柱的计算相对复杂,一般通过查表或特定公式,简化版不考虑闰月复杂情况
    day_offset = (lunar.day + (lunar.year - 1900) * 365) % 60
    day_pillar = get_heavenly_stem_and_earthly_branch(day_offset)

    # 计算时柱
    hour_offset = (hour + 1) // 2 % 12
    hour_pillar = get_heavenly_stem_and_earthly_branch(day_offset % 10 * 2 + hour_offset)

    return year_pillar, month_pillar, day_pillar, hour_pillar

# 示例:计算1988年5月23日14时的生辰八字
year, month, day, hour = 1956, 4, 14, 3
bazi = calculate_bazi(year, month, day, hour)
print("生辰八字:", bazi)
三、运行结果

赶紧来试试吧。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值