欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现的阳历转阴历(农历)算法

程序员文章站 2023-10-17 19:25:41
搜索了好几个python实现的万年历多有部分时间有问题,好多是来自这个代码: 复制代码 代码如下:#!/usr/bin/env python# -*- coding: u...


搜索了好几个python实现的万年历多有部分时间有问题,好多是来自这个代码:

复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
usage:  ccal month [4-digit-year]
   or:  ccal 4-digit-year month

this python script is to show solar and lunar calender at the
same time. you need to have python (2.0 or above) installed.

acceptable date range:  1900/2 -- 2049/12

output contains chinese characters (mainland gb2312 encoding),
must be viewed in a chinese-enabled system or "cxterm" etc.
programms under unix x-windows.

the major reference for me to compose this program is:
lunar-2.1.tgz (1992), composed by
    fung f. lee <lee@umunhum.stanford.edu> and
    ricky yeung  <ricky.yeung@eng.sun.com> .

and lee and yeung refered to:
    1. "zhong1guo2 yin1yang2 ri4yue4 dui4zhao4 wan4nian2li4"
 by lin2 qi3yuan2. 《中国阴阳日月对照万年历》.林
    2. "ming4li3 ge2xin1 zi3ping2 cui4yan2" by xu2 le4wu2.
 《命理革新子平粹言》.徐
    3.  da1zhong4 wan4nian2li4. 《大众万年历》

license:
    gnu general public license (gpl, see http://www.gnu.org).
    in short, users are free to use and distribute this program
    in whole. if users make revisions and distribute the revised
    one, they are required to keep the revised source accessible
    to the public.

version:
    0.3.2,  jan/16/2007, according to sprite's information, changed 3 codes:
            1954: 0x0a5d0 --> 0x0a5b0, 1956: 0x052d0 --> 0x052b0
            1916: 0x0d6a0 --> 0x056a0
    0.3.1,  jan/15/2007, changed 1978's code from 0xb5a0 to 0xb6a0.
            a young lady's birth day (lunar 1978/8/4) problem reported
            on internet -- informed by sprite at linuxsir.org
    0.3.0,  sep/25/2006, add coding line, prevent python to report warning
    0.2.0,  jan/6/2002, shengxiao(生肖), lunar leap month(闰月)
            added.
    0.1.0,  jan/4/2002

 --- changsen xu <xucs007@yahoo.com>
'''

#remember, in this program:
#   month=0 means januaray, month=1 means february ...;
#   day=0 means the first day of a month, day=1 means the second day,
#       so as to ease manipulation of python lists.
#   year=0 is 1900, until the last step to output

daysinsolarmonth= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
lunarmonthdays  = [29,30] # a short (long) lunar month has 29 (30) days */

shengxiaoen     = ["mouse", "ox", "tiger", "rabbit", "dragon", "snake",
                   "horse", "goat", "monkey", "rooster", "dog", "pig"]
shengxiaogb     = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡",
                   "狗", "猪"]
zhigb           = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉",
                   "戌", "亥"]
gangb           = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]

monthen         = ['january', 'february', 'march', 'april', 'may', 'june',
                   'july', 'august', 'september', 'october', 'november',
                   'december']
weekdayen       = ["monday", "tuesday", "wednesday", "thursday",
                   "friday", "saturday", "sunday"]
weekdaygb       = ["一", "二", "三", "四", "五", "六", "日"]
numgb           = ['○', "一", "二", "三", "四", "五", "六", "七", "八", "九",
                   "十"]
lunarholiday    = {'0_0':'春节', '4_4':'端午', '7_14':'中秋', '8_8':'重阳',
                   '0_14':'元宵'}


#   encoding:
#        b bbbbbbbbbbbb bbbb
#      bit#     1 111111000000 0000
#               6 543210987654 3210
#     . ............ ....
#      month#   000000000111
#               m 123456789012   l
#          
#   b_j = 1 for long month, b_j = 0 for short month
#   l is the leap month of the year if 1<=l<=12; no leap month if l = 0.
#   the leap month (if exists) is long one if m = 1.
yearcode = [
         0x04bd8, # 1900
    0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, # 1905
    0x16554, 0x056a0, 0x09ad0, 0x055d2, 0x04ae0, # 1910
    0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, # 1915
    0x056a0, 0x0ada2, 0x095b0, 0x14977, 0x04970, # 1920
    0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, # 1925
    0x02b60, 0x09570, 0x052f2, 0x04970, 0x06566, # 1930
    0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, # 1935
    0x186e3, 0x092e0, 0x1c8d7, 0x0c950, 0x0d4a0, # 1940
    0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, # 1945
    0x092d0, 0x0d2b2, 0x0a950, 0x0b557, 0x06ca0, # 1950
    0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, # 1955
    0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, 0x0aea6, # 1960
    0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, # 1965
    0x0f263, 0x0d950, 0x05b57, 0x056a0, 0x096d0, # 1970
    0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, # 1975
    0x0d558, 0x0b540, 0x0b6a0, 0x195a6, 0x095b0, # 1980
    0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, # 1985
    0x06d40, 0x0af46, 0x0ab60, 0x09570, 0x04af5, # 1990
    0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, # 1995
    0x055c0, 0x0ab60, 0x096d5, 0x092e0, 0x0c960, # 2000
    0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, # 2005
    0x0abb7, 0x025d0, 0x092d0, 0x0cab5, 0x0a950, # 2010
    0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, # 2015
    0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, # 2020
    0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, # 2025
    0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, 0x05aa0, # 2030
    0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, # 2035
    0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, 0x0b5a0, # 2040
    0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, # 2045
    0x0aa50, 0x1b255, 0x06d20, 0x0ada0   # 2049
]
yearscoded = len(yearcode)


from sys import argv, exit, stdout
from time import time, localtime
ow=stdout.write

 

class lunaryearinfo:
    def __init__(self):
        self.yeardays = 0
        self.monthdays = [0]*13
        self.leapmonth = -1  # -1 means no lunar leap month

yearinfo = [0]*yearscoded #global variable
for i in range(yearscoded):
    yearinfo[i] = lunaryearinfo()

 

class date:
    def __init__(self, year, month, day, weekday=-1, gan=-1, zhi=-1):
        self.year   =year
        self.month  =month
        self.day    =day
        self.weekday=weekday
        self.gan    =gan
        self.zhi    =zhi

solar1st = date(0, 0, 30, weekday=2)   #wednesday, january 31, 1900
lunar1st = date(0, 0, 0,  weekday=2, gan=6, zhi=0)
#wednesday, first day, first month, 1900, 庚子年

 

def error(msg):
    print 'error:', msg; exit(0)

 

def issolarleapyear (year):
    year=year+1900
    return (year%4 == 0) and (year%100 != 0) or (year%400 == 0)

 

baseyear=1201 - 1900
# in fact, real baseyear=1201.  in order to ease calculation of
# leap years. real baseyear must conform to:
#   realbaseyear%4==1 and realbaseyear%400==1.
# assert realbaseyear < solar1st.year .

# compute the number of days from the solar first date
# month=0 means january, ...
def solardaysfrombaseyear(d):    #d is a date class
    delta = d.year - baseyear
    offset = delta*365 + delta/4 - delta/100 + delta/400
    for i in range(d.month):
     offset += daysinsolarmonth[i];
    if d.month>1 and issolarleapyear(d.year):
 offset += 1
    offset += d.day
##   print '___', year, month, day, 'offset=', offset ########
    return offset

# compute the number of days from the solar first date
# month=0 means january, ..., year=0 means 1900, ...
def solardaysfromfirstdate (d): #d is a date class
    return solardaysfrombaseyear (d) - solardaysfrombaseyear (solar1st)

 

def calclunardayspermonth(iyear):
    code = yearcode[iyear]
    leapmonth = code&0xf #leapmonth==0 means no lunar leap month

    code >>= 4
    for imonth in range(12):
        yearinfo[iyear].monthdays[11-imonth] = lunarmonthdays [code&0x1]
        code >>= 1

    if leapmonth>0:
        yearinfo[iyear].leapmonth = leapmonth-1
        yearinfo[iyear].monthdays.insert (leapmonth,
                lunarmonthdays [code & 0x1])
 


def calcalllunaryearsinfo():
    for iyear in range(yearscoded):
        calclunardayspermonth (iyear)
        for imonth in range(13):
     yearinfo[iyear].yeardays += yearinfo[iyear].monthdays[imonth]

 


#input datesolar, return (datelunar, islunarmonthornot)
def solar2lunar(d): #d is a date class
    dlunar = date(-1, -1, -1) #unknown lunar date class

    offset = solardaysfromfirstdate(d)

    dlunar.weekday  = (offset + solar1st.weekday)%7

    for iyear in range(yearscoded):
        if offset < yearinfo[iyear].yeardays:
            dlunar.year = iyear; break
 offset -= yearinfo[iyear].yeardays
    if dlunar.year == -1:   error ("date out of range.")

    dlunar.gan      = (dlunar.year + lunar1st.gan) % 10
    dlunar.zhi      = (dlunar.year + lunar1st.zhi) % 12

    for imonth in range(13):
        if offset< yearinfo[dlunar.year].monthdays[imonth]:
            dlunar.month = imonth; break
 offset -= yearinfo[dlunar.year].monthdays[imonth]

    dlunar.day = offset

    isleapmonth=0
    if yearinfo[dlunar.year].leapmonth >=0:
        if dlunar.month ==  yearinfo[iyear].leapmonth + 1:
            isleapmonth=1
        if dlunar.month > yearinfo[dlunar.year].leapmonth:
            dlunar.month -= 1

    return (dlunar, isleapmonth)

 

def getsolardaysinmonth (year, month):
    if issolarleapyear(year) and month==1:
            return 29
    else:   return daysinsolarmonth[month]


def num2gb (num):
    if num==10:
        return '十'
    elif num>10 and num<20:
        return '十' + numgb[num-10]

    tmp=''
    while num>10:
        tmp = numgb[num%10] + tmp
        num = int(num/10)
    tmp = numgb[num] + tmp
    return tmp


def lunardate2gb (dlunar, isleapmonth):
    tmp = str(dlunar.month)+'_'+str(dlunar.day)
    if lunarholiday.has_key( tmp ):
        return '[0;33;44m%s[0m  '% lunarholiday[tmp] + \
               ' '*(6-len(lunarholiday[tmp]))
    elif dlunar.day==0:   
        tmp2 = '闰'*isleapmonth + num2gb(dlunar.month+1) +'月'
        return '[7m%s[0m' % tmp2 + ' '*(8-len(tmp2))
    elif dlunar.day<10:
        return '初' + num2gb(dlunar.day+1)
    else:
        return num2gb(dlunar.day+1)


def outputcalendar(year, month):
    dlunar = date(-1,-1,-1)
    ow ('\n     阳历%d年%d月         ' % (year+1900, month+1) )

    for iday in range( getsolardaysinmonth(year, month) ):
        dsolar = date(year, month, iday)
        dlunar, isleapmonth = solar2lunar (dsolar)

        if iday==0:
            ow ('始于 阴历%s年%s%s月 (%s%s年, 生肖属%s)\n' %
                ( num2gb(dlunar.year+1900), '闰'*isleapmonth,
                  num2gb(dlunar.month+1),
                  gangb [dlunar.gan], zhigb[dlunar.zhi], shengxiaogb[dlunar.zhi]
                ))
            ow ('='*74 + '\n')
            for i in range(7):
                ow ("%3s %2s     " % (weekdayen[i][:3], weekdaygb[i]) )
            ow('\n\n')
            for i in range(dlunar.weekday): ow(' '*11)

        elif dlunar.weekday==0: ow('\n')

        ow ( "%2d %-8s" %(iday+1, lunardate2gb(dlunar, isleapmonth) ) )
    ow('\n\n')

 


def checkargv (argv):
    argc = len(argv)
    if argc==1 or argv[1] in ('-h', '--help'):
        print __doc__; exit(0)

    #in case people input arguments as "4-digit-year month"
    if argc==3 and len(argv[1]) == 4 and len(argv[2]) in (1,2):
        argv[1], argv[2] = argv[2], argv[1]

   
    #get month
    month=-1
    for imonth in range(12):
        if argv[1].lower() == monthen[imonth].lower() or \
           argv[1].lower() == monthen[imonth][:3].lower():
               month = imonth+1; break
    if month==-1:
        month = eval(argv[1])

    if month<1 or month>12:     error ("month not within 1--12.")

    #get year
    if argc==2: year = localtime(time())[0]
    else:
        if len(argv[2]) != 4:   error ("year must be 4 digits.")
        year = eval(argv[2])
        if year<1900 or year>= 1900+yearscoded or (year==1900 and month==1):
            error ("year must be within %d--%d, excluding 1900/1."
                    % (1900, 1900 + yearscoded-1) )

    return year-1900, month-1

year, month = checkargv(argv)
calcalllunaryearsinfo()
outputcalendar(year, month)

这个也有问题(1989年8月的数据转换成农历就有问题)

看了好几个程序,发现实现这个并不需要什么nb的算法(好像也不存在这样的算法)可以直接实现阳历转为阴历的,都是记录了一堆阴历的数据,然后根据和基本时间来算相差几天来计算的,所有阴历数据的正确性决定了这个程序的正确性。

同学给了一个lua的程序,我试了一下,还没有找到错误的,先直接给上程序(直接从lua转成python的,写的比较乱)

复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math


def getdayof(st):
    #–天干名称
    ctiangan = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
    #–地支名称
    cdizhi = ["子","丑","寅","卯","辰","巳","午", "未","申","酉","戌","亥"]
    #–属相名称
    cshuxiang = ["鼠","牛","虎","兔","龙","蛇", "马","羊","猴","鸡","狗","猪"]
    #–农历日期名
    cdayname =[
        "*","初一","初二","初三","初四","初五",
        "初六","初七","初八","初九","初十",
        "十一","十二","十三","十四","十五",
        "十六","十七","十八","十九","二十",
        "廿一","廿二","廿三","廿四","廿五",
        "廿六","廿七","廿八","廿九","三十"
    ]
    #–农历月份名
    cmonname = ["*","正","二","三","四","五","六", "七","八","九","十","十一","腊"]

    #–公历每月前面的天数
    wmonthadd = [0,31,59,90,120,151,181,212,243,273,304,334]
    #– 农历数据
    wnonglidata = [2635,333387,1701,1748,267701,694,2391,133423,1175,396438
    ,3402,3749,331177,1453,694,201326,2350,465197,3221,3402
    ,400202,2901,1386,267611,605,2349,137515,2709,464533,1738
    ,2901,330421,1242,2651,199255,1323,529706,3733,1706,398762
    ,2741,1206,267438,2647,1318,204070,3477,461653,1386,2413
    ,330077,1197,2637,268877,3365,531109,2900,2922,398042,2395
    ,1179,267415,2635,661067,1701,1748,398772,2742,2391,330031
    ,1175,1611,200010,3749,527717,1452,2742,332397,2350,3222
    ,268949,3402,3493,133973,1386,464219,605,2349,334123,2709
    ,2890,267946,2773,592565,1210,2651,395863,1323,2707,265877]

    #—取当前公历年、月、日—
    wcuryear = st["year"]
    wcurmonth = st["mon"]
    wcurday = st["day"]
    #—计算到初始时间1921年2月8日的天数:1921-2-8(正月初一)—
    #nthedate = (wcuryear – 1921) * 365 + (wcuryear – 1921)/4 + wcurday + wmonthadd[wcurmonth] – 38
    nthedate = (wcuryear – 1921) * 365 + (wcuryear – 1921)/4 + wcurday + wmonthadd[wcurmonth-1] – 38
    if (((wcuryear % 4) == 0) and (wcurmonth > 2)):
        nthedate = nthedate + 1

    #–计算农历天干、地支、月、日—
    nisend = 0
    m = 0
    while nisend != 1:
        #if wnonglidata[m+1] < 4095:
        if wnonglidata[m] < 4095:
            k = 11
        else:
            k = 12
        n = k
        while n>=0:
            nbit = wnonglidata[m]
            for i in range(n):
                nbit = math.floor(nbit/2);

            nbit = nbit % 2

            if nthedate <= (29 + nbit):
                nisend = 1
                break

            nthedate = nthedate – 29 – nbit
            n = n – 1

        if nisend != 0:
            break
        m = m + 1

    wcuryear = 1921 + m
    wcurmonth = k – n + 1
    wcurday = int(math.floor(nthedate))
    if k == 12:
        if wcurmonth == wnonglidata[m] / 65536 + 1:
            wcurmonth = 1 – wcurmonth
        elif wcurmonth > wnonglidata[m] / 65536 + 1:
            wcurmonth = wcurmonth – 1

    print '阳历', st["year"], st["mon"], st["day"]
    print '农历', wcuryear, wcurmonth, wcurday
    #–生成农历天干、地支、属相 ==> wnongli–
    szshuxiang = cshuxiang[(((wcuryear - 4) % 60) % 12) + 1]
    szshuxiang = cshuxiang[(((wcuryear - 4) % 60) % 12) + 1]
    znongli = szshuxiang + '(' + ctiangan[(((wcuryear - 4) % 60) % 10)] + cdizhi[(((wcuryear - 4) % 60) % 12)] + ')年'
    #–sznongli,"%s(%s%s)年",szshuxiang,ctiangan[((wcuryear - 4) % 60) % 10],cdizhi[((wcuryear - 4) % 60) % 12]);

    #–生成农历月、日 ==> wnongliday–*/
    if wcurmonth < 1:
        sznongliday =  "闰" + cmonname[(-1 * wcurmonth)]
    else:
        sznongliday = cmonname[wcurmonth]

    sznongliday =  sznongliday + "月" + cdayname[wcurday]
    print sznongliday
    #return sznongli .. sznongliday


def main():
    st = {"year": 1989, "mon": 8, "day": 1}
    getdayof(st)
    st1 = {"year": 2013, "mon": 10, "day": 7}
    getdayof(st1)
    st1 = {"year": 2013, "mon": 10, "day": 1}
    getdayof(st1)
    #print("" .. getdayof(st))
main()

数据基本上正确了,根据自己的需要改一改程序就可以了。以后有时间在改好一点的。