def test_delta(self): sd = date(2018, 12, 1) self.assertEqual(-1, LCalendars.delta(sd, date(2018, 12, 2))) self.assertEqual( -1, LCalendars.delta(LunarDate.from_solar(sd), date(2018, 12, 2))) self.assertEqual( 4, LCalendars.delta(LunarDate(2018, 1, 6), LunarDate(2018, 1, 2)))
def test_term_ganzhi_feature(self): ld = LunarDate(2018, 6, 26) self.assertEqual(datetime.date(2018, 8, 7), ld.to_solar_date()) self.assertEqual(43287, ld._offset) self.assertEqual('立秋', ld.term) self.assertEqual('戊戌', ld.gz_year) self.assertEqual('庚申', ld.gz_month) self.assertEqual('辛未', ld.gz_day) self.assertEqual('二〇一八年六月廿六日', ld.cn_str()) self.assertEqual('戊戌年庚申月辛未日', ld.gz_str())
def test_timedelta(self): ld = LunarDate(1976, 8, 8) sd = date(2008, 1, 1) td = timedelta(days=10) self.assertEqual(timedelta(days=0), ld - ld) self.assertEqual(LunarDate(1976, 7, 27, 0), ld - td) self.assertEqual(timedelta(11444), sd - ld) self.assertEqual(LunarDate(1976, 8, 18, 0), ld + td) self.assertEqual(LunarDate(1976, 8, 18, 0), td + ld)
def test_edge_dates(self): # Max date self.assertEqual(MAX_OFFSET, LunarDate.max.offset) self.assertEqual(MAX_OFFSET, (LunarDate.max - LunarDate.min).days) self.assertEqual(MAX_OFFSET + 1, sum(YEAR_DAYS)) self.assertEqual(0, (LunarDate.min - MIN_SOLAR_DATE).days) self.assertEqual(0, (LunarDate.max - MAX_SOLAR_DATE).days) sd2100_ld = LunarDate.from_solar_date(2100, 12, 31) self.assertEqual('庚申年戊子月丁未日', sd2100_ld.gz_str()) sd2101_ld = LunarDate.from_solar_date(2101, 1, 28) self.assertEqual('庚申年己丑月乙亥日', sd2101_ld.gz_str())
def test_convert_datetime(self): dt = LunarDate(1976, 8, 8, 1).to_solar_date() self.assertEqual(date(1976, 10, 1), dt) dt2 = LunarDate.from_solar_date(2033, 10, 23) self.assertTrue(LunarDate(2033, 10, 1, 0), dt2) # day out of range with self.assertRaises(ValueError): LunarDate(2004, 1, 30).to_solar_date() # year out of range [1900, 2100] with self.assertRaises(ValueError): LunarDate(2101, 1, 1).to_solar_date()
def validate_lunar(): t1 = time.time() total = 0 fail = 0 records = [] for sd in iter_solar_date(): ld = LunarDate.from_solar(sd) # test target actual = ld.strftime('%y,%m,%d,%l') solar = Solar(sd.year, sd.month, sd.day) solar_date_str = '{},{},{}'.format(sd.year, sd.month, sd.day) lunar = converter.SolarToLunar(solar) expected = '{},{},{},{}'.format(lunar.lunarYear, lunar.lunarMonth, lunar.lunarDay, int(lunar.isleap)) # solar_date_str = sd.strftime("%Y,%m,%d") # rsp = urllib.request.urlopen(url='http://localhost:1337/?src={}'.format(solar_date_str)) # expected = rsp.read().decode('utf8') total += 1 if actual != expected: records.append('{} {} {}'.format(solar_date_str, expected, actual)) fail += 1 if fail > 0: with open('fail_record.txt', 'w') as fp: fp.write('\n'.join(records)) t2 = time.time() print('Completed! total:{}, fail:{};time {}s'.format(total, fail, int(t2 - t1)))
def calc_(nongli): if nongli == 1: today = LunarDate.today() res = today.cn_month + today.cn_day return res if nongli == 0: cudate = datetime.datetime.now() res = cudate.strftime("%m-%d") return res
def main(list): # list = [ # ['12-25', 'test1'] #第一个是农历生日,第二个是名字 # ] # 获取今天的农历日期 today = LunarDate.today() year = today.year month = today.month day = today.day for i, name in list: i = i.split('-') tmpMonth = int(i[0]) tmpDay = int(i[1]) tmpNow = LunarDate(year, tmpMonth, tmpDay) # print(tmpNow) dis = today - tmpNow dis = dis.days message = None if dis == 0: message = '今天' elif dis == -1: message = '明天' elif dis == -2: message = '后天' elif dis == -3: message = '大后天' # 若在范围内 if message: # 转化为公历 solarDay = tmpNow.to_solar_date() try: message = message + '是' + name + '的生日' + ' 具体日期是: ' + str( solarDay) facade.update(message, flag=True) except: pass else: facade.update(message=name + '的生日 今天不需要通知')
def test_fuzzy_feature(self): ss = SolarSchema(month=4, day=1) with self.assertRaises(ValueError): ss.resolve() self.assertEqual(date(2018, 4, 1), ss.resolve(2018)) dls = DayLunarSchema(month=12, day=1, reverse=1) self.assertEqual(1, (LunarDate(2019, 1, 1) - dls.resolve(2018)).days) schema = get_festival('元旦') self.assertTrue(schema.match(date(2019, 1, 1)))
def test_match(self): md = SolarSchema(year=0, month=2, day=14) self.assertTrue(md.match(date(2019, 2, 14))) self.assertTrue(md.match(date(2020, 2, 14))) self.assertFalse(md.match(date(2019, 2, 1))) md1 = LunarSchema(year=0, month=1, day=2) self.assertTrue(md1.match(LunarDate(2018, 1, 2))) with self.assertRaises(TypeError): md1.match(2)
def _normalize(self, date_obj): date_class = self._get_date_class() if not isinstance(date_obj, (date, LunarDate)): raise TypeError('Unsupported type: {}'.format( date_obj.__class__.__name__)) if isinstance(date_obj, date_class): return date_obj if isinstance(date_class, date): return date_obj.to_solar_date() else: return LunarDate.from_solar(date_obj)
def settime(self): a,b,c,d=time.strftime('%Y'),time.strftime('%m'),time.strftime('%d'),int(time.strftime('%w')) e={1:'星期一',2:'星期二',3:'星期三',4:'星期四',5:'星期五',6:'星期六',0:'星期日'} f=e[d] nl=LunarDate.from_solar_date(int(a),int(b),int(c)) g,h,i,j=nl.gz_year,nl.animal,nl.cn_month,nl.cn_day today1=a+'年'+b+'月'+c+'日'+f todaynl='%s(%s)年%s%s%s'%(g,h,i,j,f) time1=time.strftime('%H:%M:%S') self.var1.set(todaynl) self.var2.set(today1) self.var3.set(time1) self.root.after(1000,self.settime)
def lunardate_sqlite3_demo(): con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute( 'CREATE TABLE member (pid INT AUTO_INCREMENT PRIMARY KEY,birthday lunardate);' ) ld = LunarDate(2018, 5, 3) cur.execute("INSERT INTO member(birthday) VALUES (?)", (ld, )) cur.execute("SELECT pid, birthday FROM member;") my_birthday = cur.fetchone()[1] cur.close() con.close() print(my_birthday)
def notifyBirthday(self): # 距离生日7 、3 、1 、0天时通知 flag = False #标记今天没有人过生日 for name, birthday in self.__birthdayDict.items(): ##获取今天的农历日期 todayNongli = LunarDate.today() birthday = LunarDate(todayNongli.year, birthday.month, birthday.day, 0) #将生日的年份改成今年,方便计算还有多少天过生日,直接与当前农历日志相减 howMuchDays = birthday.offset - todayNongli.offset if (howMuchDays == 7 or howMuchDays == 3 or howMuchDays == 1 or howMuchDays == 0): text = '{name}的生日还有{howMuchDays}天,要祝福呦~。'.format( name=name, howMuchDays=howMuchDays) desp = '###{name},祝你生日快乐,健健康康~~'.format( name=name) # 内容支持markdown serverJiangNoify = ServerJiangNoify(text, desp) #初始化. print(serverJiangNoify.sendMessage()) flag = True #无人过生日 text = "加油工作,加油学习~" + str(time.time()) desp = "###没钱不行,没钱不行,没钱不行~" serverJiangNoify = ServerJiangNoify(text, desp) print(serverJiangNoify.sendMessage())
def test_custom_field(self): con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute('CREATE TABLE member (pid INT AUTO_INCREMENT PRIMARY KEY,birthday lunardate);') ld = LunarDate(2018, 5, 3) cur.execute("INSERT INTO member(birthday) VALUES (?)", (ld,)) cur.execute("SELECT pid, birthday FROM member;") my_birthday = cur.fetchone()[1] cur.close() con.close() self.assertEqual(LunarDate, type(my_birthday)) self.assertEqual(2018, my_birthday.year) self.assertEqual(5, my_birthday.month) self.assertEqual(3, my_birthday.day) self.assertEqual(0, my_birthday.leap)
def main(): # 获取明天的农历日期(农历2018年七月初一) lu_date = LunarDate.tomorrow() tom_day = f"{fix_zero(lu_date.month)}{fix_zero(lu_date.day)}" # 查询数据 b_sql = f"select modify_time,name,relation,lunar_birth from birth where lunar_birth='{tom_day}'" b_data = m_load_data(b_sql) if len(b_data) > 0: # 生成邮件 msg_root = MIMEMultipart('related') msg_root['From'] = Header("Remind", 'utf-8') msg_root['To'] = "Y.G" subject = f'明日生日提醒-记得关注' msg_root['Subject'] = Header(subject, 'utf-8') msg_alternative = MIMEMultipart('alternative') b_info = "" for item in b_data: b_info += "<tr>" for var2 in range(0, 4): b_info += f"<td>{item[var2]}</td>" b_info += "</tr>" mail_msg = f""" {CSS_INFO} <h2>这些小可爱明天要过生日了,记得送祝福哦!!!</h2> <table class="pure-table pure-table-horizontal"> <thead> <tr> <th>-_-</th> <th>Name</th> <th>relation</th> <th>birth</th> </tr> </thead> <tbody> {b_info} </tbody> </table> <br/> <hr size=1 color='gray' width='600' align='left'/> """ msg_alternative.attach(MIMEText(mail_msg, 'html', 'utf-8')) msg_root.attach(msg_alternative) # 发送邮件 send_email(msg_root) else: print("明天没有过生日的人")
def test_schema_factory(self): md2 = DateSchemaFactory.from_string('1000006140') self.assertTrue(md2.match(LunarDate(2017, 6, 14))) self.assertTrue(md2.match(LunarDate(2017, 6, 14, 1))) sd = LunarDate(2017, 6, 14).to_solar_date() self.assertTrue(md2.match(sd)) md3 = DateSchemaFactory.from_string('106140') self.assertTrue(md3.match(LunarDate(2017, 6, 14))) self.assertTrue(md3.match(LunarDate(2017, 6, 14, 1))) sd = LunarDate(2017, 6, 14).to_solar_date() self.assertTrue(md3.match(sd))
def test_match(self): ls = LunarSchema(month=6, day=1) self.assertTrue(ls.match(LunarDate(2017, 6, 1, 0))) self.assertTrue(ls.match(LunarDate(2017, 6, 1, 1))) ls1 = LunarSchema(month=6, day=1, ignore_leap=0) self.assertTrue(ls1.match(LunarDate(2017, 6, 1, 0))) self.assertFalse(ls1.match(LunarDate(2017, 6, 1, 1))) ls2 = LunarSchema(month=6, day=1, leap=1, ignore_leap=0) self.assertFalse(ls2.match(LunarDate(2017, 6, 1, 0))) self.assertTrue(ls2.match(LunarDate(2017, 6, 1, 1)))
def notifyBirthday(): print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) birthdayDict = { "我": LunarDate(1986, 10, 3, 0), "婷婷": LunarDate(1987, 4, 2, 0), "东北爸": LunarDate(1967, 5, 28, 0), "东北妈": LunarDate(1965, 11, 27, 0), "湖南爸": LunarDate(1953, 9, 25, 0), "湖南妈": LunarDate(1957, 5, 29, 0), } notifyBirthday = NotifyBirthday(**birthdayDict) notifyBirthday.notifyBirthday()
def test_new_date(self): ld = LunarDate(2018, 12, 10) ld1 = ld.replace(year=2017, month=6, day=23, leap=1) self.assertEqual(2017, ld1.year)
def test_immutable_feature(self): ld1 = LunarDate(2018, 6, 1) ld2 = LunarDate(2018, 6, 1) self.assertEqual(1, len({ld1, ld2}))
def test_comparison(self): ld = LunarDate(1976, 8, 8) ld2 = LunarDate.today() self.assertTrue(ld < ld2) self.assertTrue(ld <= ld2) self.assertTrue(ld2 > ld) self.assertTrue(ld2 >= ld) self.assertTrue(ld != ld2) self.assertFalse(ld == ld2) self.assertTrue(LunarDate.today() == LunarDate.today()) # Compare with a integer self.assertFalse(LunarDate.today() == 5) with self.assertRaises(TypeError): LunarDate.today() < 5 with self.assertRaises(TypeError): LunarDate.today() > 5 with self.assertRaises(TypeError): LunarDate.today() >= 5 with self.assertRaises(TypeError): LunarDate.today() >= 5
def test_valid_format(self): ld = LunarDate(2018, 4, 3) self.assertEqual('2018-4-3', ld.strftime('%y-%m-%d')) self.assertEqual('二〇一八', ld.strftime('%Y')) self.assertEqual('2018%c', ld.strftime('%y%c')) # Just ignore %c, no raise error ld2 = LunarDate(2018, 11, 23) self.assertEqual('二〇一八/冬/廿三', ld2.strftime('%Y/%M/%D')) ld3 = LunarDate(2017, 6, 3, 1) self.assertEqual('61', ld3.strftime('%m%l')) self.assertEqual('闰六', ld3.strftime('%L%M')) self.assertEqual(ld3.gz_str(), ld3.strftime('%G')) self.assertEqual('%y', ld3.strftime('%%y')) self.assertEqual('%2017', ld3.strftime('%%%y')) self.assertEqual('2017631', ld3.strftime('%y%m%d%l')) self.assertEqual('201706031', ld3.strftime('%y%A%B%l'))
def test_edge_dates(self): # Max date self.assertEqual(MAX_OFFSET, LunarDate.max.offset) sd2100_ld = LunarDate.from_solar_date(2100, 12, 31) self.assertEqual('庚申年戊子月丁未日', sd2100_ld.gz_str())
def test_create_date(self): ld = LunarDate(1976, 8, 8, 1) self.assertEqual(1976, ld.year) self.assertEqual(8, ld.month) self.assertEqual(8, ld.day) self.assertEqual(True, ld.leap)
def test_leap_countdown(self): ls = LunarSchema(month=6, day=1) ls.delta(LunarDate(2017, 6, 27))
def __render_one_day_info(self, row, date, info_frame=None): if info_frame is None: info_frame = self.info_frame for widget in info_frame.winfo_children(): widget.destroy() str_date = date.strftime('%Y-%m-%d') # 渲染某个日期的基本信息 tk.Label(info_frame, text='-' * Constants.SPLIT_LINE, font=(Constants.FONT, Constants.FONT_SIZE_14, Constants.FONT_WEIGHT)).grid(row=row + 1, column=0, columnspan=7, sticky=tk.N) tk.Label(info_frame, text=date.day, width=2, height=1, fg=Constants.WHITE_COLOR, bg=Constants.ORANGE_COLOR, font=(Constants.FONT, 50, Constants.FONT_WEIGHT)).grid(row=row + 2, column=0, rowspan=3, columnspan=2, sticky=tk.W, padx=3) solar_date = date.strftime('%Y{0}%m{1}%d{2} {3}{4}').format( '年', '月', '日', '星期', Constants.WEEKS[date.weekday()]) tk.Label(info_frame, text=solar_date, fg=Constants.BLACK_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_12, Constants.FONT_WEIGHT)).grid(row=row + 2, column=1, columnspan=6, sticky=tk.NW, padx=20) lunar_date = LunarDate.from_solar(date) lunar_date = lunar_date.strftime('{0}%M{1}%D %G'.format('农历:', '月')) tk.Label(info_frame, text=lunar_date, fg=Constants.BLACK_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_10, Constants.FONT_WEIGHT)).grid(row=row + 3, column=1, columnspan=6, sticky=tk.NW, padx=21) # 渲染24节气 twenty_four_day = self.tf.get_festivals(str_date) if twenty_four_day: twenty_four_day = twenty_four_day[0] + '\r' + twenty_four_day[1] tk.Label(info_frame, text=twenty_four_day, fg=Constants.WHITE_COLOR, bg=Constants.GREEN_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_10)).grid(row=row + 4, column=1, sticky=tk.NW, padx=22) # 渲染农历节日 lunar_day = LunarDate.from_solar(date).strftime('%M%D') lunar_festival = self.lf.get_festivals(lunar_day) if lunar_festival: tk.Label(info_frame, text=lunar_festival, fg=Constants.WHITE_COLOR, bg=Constants.ORANGE_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_10, Constants.FONT_WEIGHT)).grid(row=row + 4, column=1, sticky=tk.E) # 母亲节 父亲节 感恩节 如果与公历节日冲突则覆盖公历节日 parents_day = self.pd.get_festivals(str_date) if parents_day: tk.Label(info_frame, text=parents_day, fg=Constants.WHITE_COLOR, bg=Constants.RED_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_10, Constants.FONT_WEIGHT)).grid(row=row + 4, column=2, sticky=tk.W) # 渲染公历节日 solar_day = self.sf.get_festivals_desc(date.strftime('%m-%d')) if solar_day: tk.Label(info_frame, text=solar_day, fg=Constants.WHITE_COLOR, bg=Constants.RED_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_10, Constants.FONT_WEIGHT)).grid(row=row + 4, column=3, sticky=tk.W, columnspan=4) # 渲染日程信息 tk.Label(info_frame, text='-' * Constants.SPLIT_LINE, font=(Constants.FONT, Constants.FONT_SIZE_14, Constants.FONT_WEIGHT)).grid(row=row + 6, column=0, columnspan=7, sticky=tk.N) sch_list = self.sl.get_today_schedulers(str_date) if sch_list and len(sch_list) > 0: index = 7 sch_bg = Constants.SCHEDULER_COLOR if date < self.today: sch_bg = Constants.GREY_COLOR tk.Label(info_frame, text='待办事项:', fg=Constants.WHITE_COLOR, bg=Constants.SCHEDULER_COLOR, font=(Constants.FONT, Constants.FONT_SIZE_10)).grid(row=row + index, column=0, columnspan=6, sticky=tk.NW, padx=3) for sch in sch_list: sch_info = '%02s:%02s - %s:%s' % (str( sch.get('hour')), str(sch.get('minute')), sch.get('title'), sch.get('describ')) tk.Label(info_frame, text=sch_info, fg=Constants.WHITE_COLOR, bg=sch_bg, font=(Constants.FONT, Constants.FONT_SIZE_10, Constants.FONT_WEIGHT)).grid(row=row + index + 1, column=1, columnspan=6, sticky=tk.W, pady=3) index += 1
def test_countdown_lunar(self): ls = LunarSchema(year=0, month=4, day=2) self.assertEqual(1, ls.countdown(LunarDate(2019, 4, 1))) self.assertEqual(0, ls.countdown(LunarDate(2019, 4, 2))) self.assertEqual(353, ls.countdown(LunarDate(2019, 4, 3)))
def test_solar_and_lunar(self): ld = LunarDate.today() sd = ld.to_solar_date() self.assertEqual(ld.weekday(), sd.weekday()) self.assertEqual(ld.isoweekday(), sd.isoweekday())
# borax==3.3.1 from borax.calendars.lunardate import LunarDate from 农历生日计算与提醒判断 import facade list = [ '12-26', # 农历生日 ] # 获取今天的农历日期 today = LunarDate.today() today_string = today.strftime('%m-%d') year = today.year month = today.month day = today.day for i in list: i = i.split('-') tmpMonth = int(i[0]) tmpDay = int(i[1]) tmpNow = LunarDate(year, tmpMonth, tmpDay) # print(tmpNow) dis = today - tmpNow dis = dis.days message = None if dis == 0: message = '今天' elif dis == -1: message = '明天' elif dis == -2: