def update_lunar_month(cls): now = datetime.datetime.now() for date in Lunchdate.objects.filter(date__gte=now): solar = Solar(date.date.year, date.date.month, date.date.day) lunar = Converter.Solar2Lunar(solar) if lunar.day == 1 or lunar.day == 15: date.veggie = True date.save()
def tinh_nam_am_lich(nam_duong, thang_duong, ngay_duong): solar = Solar(nam_duong, thang_duong, ngay_duong) lunar = Converter.Solar2Lunar(solar) nam_am_lich = int(lunar.year) thang_am_lich = lunar.month ngay_am_lich = lunar.day return ngay_am_lich, thang_am_lich, nam_am_lich
def check_birthday(self): p = self.bir.split('\n') if not p: print('not exist file') return self.solar_today = datetime.date.today() self.lunar_today = Converter.Solar2Lunar( Solar(self.solar_today.year, self.solar_today.month, self.solar_today.day)) info = [] for i in p: if i == '': continue name_birthday = i.split(':')[0] solar_birthday = i.split(':')[1].replace(' ', '') solar_day = int(solar_birthday.split('/')[0]) solar_month = int(solar_birthday.split('/')[1]) solar_year = int(solar_birthday.split('/')[2]) # exception unknown if solar_day == 0: solar_day = 1 if solar_month == 0: solar_month = 1 if solar_year == 0: solar_year = 1900 try: lunar_birthday = Converter.Solar2Lunar( Solar(solar_year, solar_month, solar_day)) except Exception as e: print(e) print(solar_year, solar_month, solar_day) if solar_day == self.solar_today.day and solar_month == self.solar_today.month: age = int(self.solar_today.year - solar_year) info.append([age, name_birthday, 'solar']) if lunar_birthday.day == self.lunar_today.day and lunar_birthday.month == self.lunar_today.month: age = int(self.lunar_today.year - lunar_birthday.year) info.append([age, name_birthday, 'lunar']) return info
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs): sleep = random.randint(2, 10) # self.markAsDelivered(thread_id, message_object.uid) # self.markAsRead(thread_id) if author_id != self.uid: if message_object.text: if message_object.text == '/Getid' or message_object.text == '/getid': self.send(Message(text=message_object.author), thread_id=thread_id, thread_type=thread_type) elif '/tuvi' in message_object.text: tuoi = message_object.text[message_object.text. index('/tuvi') + len('/tuvi'):] tuvi = TuVi() loi_phan = tuvi.con_giap(Cgiap=tuoi) self.send(Message(text=loi_phan), thread_id=thread_id, thread_type=thread_type) elif '/hoangdao' in message_object.text: cung = message_object.text[message_object.text. index('/hoangdao') + len('/hoangdao'):] tuvi = TuVi() loi_phan = tuvi.cung_hoang_dao(cung_hd=cung) # print('loi phan cua toi la {}'.format(loi_phan)) self.send(Message(text=loi_phan), thread_id=thread_id, thread_type=thread_type) elif '/lich' in message_object.text: time.sleep(sleep) solar_today = datetime.date.today() lunar_today = Converter.Solar2Lunar( Solar(solar_today.year, solar_today.month, solar_today.day)) self.send(Message( text= "Hôm nay, \nDương lịch: {}-{}-{}\nÂm lịch: {}-{}-{}" .format(solar_today.day, solar_today.month, solar_today.year, lunar_today.day, lunar_today.month, lunar_today.year)), thread_id=thread_id, thread_type=thread_type) else: time.sleep(sleep) self.send(Message(text=other_text), thread_id=thread_id, thread_type=thread_type) else: time.sleep(sleep) self.send(Message(text=other_text), thread_id=thread_id, thread_type=thread_type)
def get_lunar_calendar_features(t): """ Trích xuất các feature âm lịch (tháng âm, ngày âm, tháng nhuận) từ date """ date = t.date() lunar = Converter.Solar2Lunar(date) return pd.Series({ 'LunarMonth': lunar.month, 'LunarDayOfMonth': lunar.day, 'LeapMonth': lunar.isleap })
def __init__(self): self.solar_today = datetime.date.today() self.lunar_today = Converter.Solar2Lunar( Solar(self.solar_today.year, self.solar_today.month, self.solar_today.day)) try: r = requests.get( 'https://docs.google.com/document/u/1/export?format=txt&id=1IhOEAR_NxDysdJJKdkzDhW6VQEnCshReO8_mynJB92s&token=AC4w5Vjy32Zj7v46kp92pRpnaRv9crJ1hA%3A1619984863716&ouid=112541721323011351705&includes_info_params=true&inspectorResult=%7B%22pc%22%3A1%2C%22lplc%22%3A12%7D' ) bir = r.text self.bir = bir except Exception as e: print(e)
def change_lunch(cls, list_date, request_off): for date_off in list_date: user_lunch = UserLunch.objects.filter( profile_id=request_off.profile.id, date=date_off.date) if date_off.lunch: if not user_lunch.exists(): data = {'date': date_off.date} solar = Solar(date_off.date.year, date_off.date.month, date_off.date.day) lunar = Converter.Solar2Lunar(solar) if request_off.profile.veggie and (lunar.day == 15 or lunar.day == 1): data['has_veggie'] = True UserLunch.objects.create( date=data.get('date'), has_veggie=data.get('has_veggie', False), profile_id=request_off.profile.id, ) else: if user_lunch.exists(): user_lunch.delete()
def s2l(yy): ''' solar date to lunar date ''' ss = Solar(yy, 2, 10) ll = Converter.Solar2Lunar(ss) print(f'{ss.to_date()} => {ll}')
# -*- coding: utf-8 -*- import traceback import datetime from lunarcalendar import Converter, Solar, Lunar, DateNotExist from lunarcalendar.festival import festivals if __name__ == '__main__': # solar converts to lunar, then converts to solar solar = Solar(2018, 1, 1) print(solar) lunar = Converter.Solar2Lunar(solar) print(lunar) solar = Converter.Lunar2Solar(lunar) print(solar) print(solar.to_date(), type(solar.to_date())) print(Solar.from_date(datetime.date(2018, 1, 1))) print('=' * 20) # lunar converts to solar, then converts to solar lunar = Lunar(2018, 2, 30, isleap=False) print(lunar) solar = Converter.Lunar2Solar(lunar) print(solar) lunar = Converter.Solar2Lunar(solar) print(lunar) print(lunar.to_date(), type(lunar.to_date())) print(Lunar.from_date(datetime.date(2018, 4, 15))) print('=' * 20)
def is_lunar_day(cls, date): solar = Solar(date.year, date.month, date.day) lunar = Converter.Solar2Lunar(solar) if lunar.day == 1 or lunar.day == 15: return True return False
def timewiz(user_data): output = [] hmsformat = ("%H:%M:%S") weekdayhmformat = ("%A %H:%M") ymdhmsformat = ("%F %H:%M:%S") fullformat = ("%A %F %H:%M:%S") countdownformat = ("{H}h {M}′ {S}″") longcountdownformat = ("{D}d {H}h {M}′") timeshown = ( # these should be chat-specific or possibly guild-specific settings ((37.791279, -122.399218), "San Francisco, San Diego"), # Union Square ((42.356528, -71.055808), "Boston, Augusta, Havana"), # Haymarket Square ((5.545631, -0.208266), "Accra"), # Rawlings Park ((52.374366, 4.898069), "Amsterdam, Bern"), # De Oude Kerk ((55.754118, 37.620386), "Moscow"), # Red Square ((1.292379, 103.852276), "Singapore, Manila, Hong Kong"), # St. Andrew's Cathedral ((-37.787329, 175.282472), "Kirikiriroa") # Garden Place ) adjustment = -37.0 # there should be admin settings for this, as we may find these need adjusting adjustment3 = -37.0 utcdt = datetime.now(timezone.utc) # utcdt = datetime(1912,1,1,10,0,0,0,timezone.utc) # for testing cwtdt = datetime.fromtimestamp(SPEED * (utcdt.timestamp() + CW_OFFSET), tz=timezone.utc) cw3tdt = datetime.fromtimestamp(SPEED * (utcdt.timestamp() + CW3_OFFSET), tz=timezone.utc) cwadt = datetime.fromtimestamp(cwtdt.timestamp() + SPEED * adjustment, tz=timezone.utc) cw3adt = datetime.fromtimestamp(cw3tdt.timestamp() + SPEED * adjustment3, tz=timezone.utc) def strfdelta(tdelta, fmt): d = {"D": tdelta.days} d["H"], rem = divmod(tdelta.seconds, 3600) d["M"], d["S"] = divmod(rem, 60) return fmt.format(**d) def get_moon(): a = astral.Astral() moon_phase = a.moon_phase(utcdt, rtype=float) lunation = moon_phase / 27.99 PRECISION = 0.05 NEW = 0 / 4.0 FIRST = 1 / 4.0 FULL = 2 / 4.0 LAST = 3 / 4.0 NEXTNEW = 4 / 4.0 phase_strings = ((NEW + PRECISION, "🌑"), (FIRST - PRECISION, "🌒"), (FIRST + PRECISION, "🌓"), (FULL - PRECISION, "🌔"), (FULL + PRECISION, "🌕"), (LAST - PRECISION, "🌖"), (LAST + PRECISION, "🌗"), (NEXTNEW - PRECISION, "🌘"), (NEXTNEW + PRECISION, "🌑")) i = bisect.bisect([a[0] for a in phase_strings], lunation) return phase_strings[i][1] sunmoon = '🌞' if (6 < cwadt.hour < 18) else '🌙' countdownArena = (datetime(1, 1, 1, 8, 15, 0, 0, timezone.utc) - utcdt) % timedelta(hours=24) countdownBattle = ((datetime(1, 1, 1, 6, 0, 0, 0, timezone.utc) - cwtdt) / SPEED) % timedelta(hours=8) countdownPeriod = ((datetime(1, 1, 1, 0, 0, 0, 0, timezone.utc) - cwadt) / SPEED) % timedelta(hours=2) nextCwMonth = ( cwadt.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + timedelta(days=32)).replace(day=1) countdownMonth = (nextCwMonth - cwadt) / SPEED season_int = ((12 * utcdt.year + utcdt.month) // 3 + 11) % 12 nextCwSeason = (utcdt.replace(year=utcdt.year + (utcdt.month == 12), month=((((utcdt.month) // 3) + 1) * 3) % 12, day=1, hour=0, minute=0, second=0, microsecond=0)) countdownSeason = (nextCwSeason - utcdt) output.append(f"<b>Chat Wars (EU)</b>:") output.append( f'{CW_WEEKDAYS[cwadt.weekday()]} {cwadt.strftime(ymdhmsformat)} (estimated)' ) output.append( f'{CW_WEEKDAYS[cwtdt.weekday()]} {cwtdt.strftime(hmsformat)} (tabular)' ) output.append( f'{sunmoon} {CW_PERIODS[cwadt.hour//6]}: {CW_PERIODS[cwadt.hour//6 + 1]} in ≈{strfdelta(countdownPeriod, countdownformat)}' ) output.append( f'⚔ next battle in {strfdelta(countdownBattle, countdownformat)}') output.append( f'📯 arena resets in {strfdelta(countdownArena, countdownformat)}') output.append( f"🗓 month of {CW_MONTHS[cwadt.month]}: {CW_MONTHS[cwadt.month+1]} in ≈{strfdelta(countdownMonth, longcountdownformat)}" ) output.append( f"{SEASON_EMOJI[season_int]} {CW_SEASONS[season_int]} season: {CW_SEASONS[season_int + 1]} in ≈{strfdelta(countdownSeason, longcountdownformat)}" ) output.append(f'') output.append( f"<b>Chat Wars 3 (RU)</b>: {CW3_WEEKDAYS[cw3adt.weekday()]} {cw3adt.strftime(hmsformat)}" ) # /time3 output.append(f'') usertz_str = user_data.get('timezone') if usertz_str: worktz = pytz.timezone(usertz_str) workdt = utcdt.astimezone(worktz) heb = dates.HebrewDate.from_pydate(workdt) heb_tom = None yin = Converter.Solar2Lunar( Solar(workdt.year, workdt.month, workdt.day)) ses = sesDate.sesDate(utcdt.timestamp(), workdt.utcoffset().total_seconds()) latlon = user_data.get('location') if latlon: loc = astral.Location( ('', '', latlon[0], latlon[1], usertz_str, 0)) sunset = loc.time_at_elevation(-.8, direction=astral.SUN_SETTING) nightfall = loc.time_at_elevation(-8.5, direction=astral.SUN_SETTING) if workdt.time() < sunset.time(): pass elif sunset.time() < workdt.time() < nightfall.time(): heb_tom = heb + 1 else: heb = heb + 1 output.append( f"<b>Your time</b>: {workdt.tzname()} (GMT{workdt.strftime('%z')})" ) output.append(f'{get_moon()} {workdt.strftime(fullformat)}') output.append( f'{heb.year} {HEB_MONTHS_ENG[heb.month]}{(" II" if heb.month == 13 else " I")if hebrewcal.Year(heb.year).leap and heb.month > 11 else ""} ' + f'{heb.day} · {hebrew_numeral(heb.day)}' + f' {HEB_MONTHS_VRT[heb.month]}{(" ב" if heb.month == 13 else " א") if hebrewcal.Year(heb.year).leap and heb.month > 11 else ""} {hebrew_numeral(heb.year)}' ) if heb_tom: heb = heb_tom output.append( f'{heb.year} {HEB_MONTHS_ENG[heb.month]}{(" II" if heb.month == 13 else " I")if hebrewcal.Year(heb.year).leap and heb.month > 11 else ""} ' + f'{heb.day} · {hebrew_numeral(heb.day)}' + f' {HEB_MONTHS_VRT[heb.month]}{(" ב" if heb.month == 13 else " א") if hebrewcal.Year(heb.year).leap and heb.month > 11 else ""} {hebrew_numeral(heb.year)}' ) output.append( f'{yin.year + SUN_YAT_SEN_ERA}/{yin.year + WRITERS_ERA}年{yin.month}月{yin.day}日' ) output.append( f'{ses.natural.year:0>5d}.{ses.natural.season:0>1d}.{ses.natural.day:0>2d} · cyclic {ses.cyclic.great}.{ses.cyclic.small}.{ses.cyclic.year}:{ses.cyclic.season}.{ses.cyclic.week}.{ses.cyclic.day}' ) output.append(f'') for worktime in timeshown: tz_str = TimezoneFinder().timezone_at(lat=worktime[0][0], lng=worktime[0][1]) tz = pytz.timezone(tz_str) workdt = utcdt.astimezone(tz) minutes = 60 * workdt.hour + workdt.minute clockface = CLOCK_EMOJI[(minutes + 10) // 30 % 24] if (clockface == '🕛'): ampmindicator = '☀️' if (11 * 60 < minutes < 13 * 60) else '⚫' else: ampmindicator = '🅰' if minutes < 12 * 60 else '🅿️' loc = astral.Location( ('', '', worktime[0][0], worktime[0][1], tz_str, 0)) loc.solar_depression = DEPRESSION if loc.sunrise(workdt) > workdt or loc.dusk(workdt) < workdt: sunprogress = '🌃' elif loc.sunset(workdt) < workdt < loc.dusk(workdt): sunprogress = '🌆' else: sunprogress = '🏙️' output.append( f'{clockface}{ampmindicator}{sunprogress} {utcdt.astimezone(tz).strftime(weekdayhmformat)} {utcdt.astimezone(tz).tzname()}' ) output.append( f" ╰ GMT{utcdt.astimezone(tz).strftime('%z')} {worktime[1]}") return '\n'.join(output)
from lunarcalendar import Solar, Converter from datetime import date, timedelta #lunars = [0x0E, 0x11, 0x12, 0x13] lunars = [0x0E] wb = Workbook() ws = wb.active ws.cell(1, 1).value = "Gregorian" for i, l in enumerate(lunars): ws.cell(1, 2 + i).value = f'Lunar {l:02X}' ws.cell(1, len(lunars) + 2).value = 'Solar2Lunar' for i in range(1, 100001): ws.cell(i + 1, 1).value = i ws.cell(i + 1, 1).number_format = 'yyyy-mm-dd' for j, l in enumerate(lunars): ws.cell(i + 1, j + 2).value = f'=TEXT({i}, "[$-{l:02X}0000]yyyy-mm-dd")' dt = date(1900, 1, 1) + timedelta(days=i - 1) try: lunar = Converter.Solar2Lunar(Solar(dt.year, dt.month, dt.day)) ws.cell(i + 1, len(lunars) + 2).value = f'{lunar.year:04}-{lunar.month:02}-{lunar.day:02}' except Exception: pass wb.save(filename=f'lunarcal.xlsx')
def emeryradio(user_data): output = [] wkdyformat = ("%A") dateformat = ("%F") timeformat = ("%H:%M") secondsformat = ("%H:%M:%S") adjustment = -37.0 #utcdt = datetime(2019,2,1,17,22,35,0,timezone.utc) utcdt = datetime.now(timezone.utc) cwtdt = datetime.fromtimestamp(3 * (utcdt.timestamp() - 11_093_806_800), tz=timezone.utc) cwadt = datetime.fromtimestamp(cwtdt.timestamp() + 3 * adjustment, tz=timezone.utc) PT = pytz.timezone("US/Pacific") MT = pytz.timezone("US/Mountain") CT = pytz.timezone("US/Central") ET = pytz.timezone("US/Eastern") GMT = pytz.timezone("Etc/GMT") CET = pytz.timezone("Europe/Zurich") IST = pytz.timezone("Asia/Kolkata") WIB = pytz.timezone("Asia/Jakarta") WPS = pytz.timezone("Asia/Singapore") heb = dates.HebrewDate.from_pydate(utcdt.astimezone(PT)) yin = Converter.Solar2Lunar( Solar( utcdt.astimezone(PT).year, utcdt.astimezone(PT).month, utcdt.astimezone(PT).day)) ses = sesDate.sesDate(utcdt.timestamp(), utcdt.astimezone(PT).utcoffset().total_seconds()) sunmoon = "🌞" if (6 < cwadt.hour < 18) else ("🌚" if (yin.day < 3) else "🌙") cwMonthNames = [ "Hailag", "Wintar", "Hornung", "Lenzin", "Ōstar", "Winni", "Brāh", "Hewi", "Aran", "Witu", "Wīndume", "Herbist", "Hailag", "Wintar" ] cwWeekdayNames = [ "Mânotag", "Ziestag", "Mittawehha", "Jhonarestag", "Frîatag", "Sunnûnabund", "Sunnûntag", "Mânotag" ] cwPeriodNames = ["Night", "Morning", "Day", "Evening", "Night"] hebMonthNames = [ "Adar", "Nisan", "Iyyar", "Sivan", "Tammuz", "Av", "Elul", "Tishrei", "Marcheshvan", "Kislev", "Tevet", "Shevat", "Adar", "Adar" ] hebMonthNamesIvrit = [ "אדר", "ניסן", "אייר", "סיוון", "תמוז", "אב", "אלול", "תשרי", "מרחשוון", "כסלו", "טבת", "שבט", "אדר", "אדר" ] timeToPeriodChange = (-(cwadt.timestamp() % 21600) + 21600) / 3 timeToBattle = (-((cwtdt.timestamp() - 21600) % 86400) + 86400) / 3 timeToArena = (-((cwtdt.timestamp() + 51300) % 259200) + 259200) / 3 output.append("<b>Current time</b>:") output.append( f'{cwWeekdayNames[int(cwadt.weekday())]} {cwadt.strftime("%Y-%m-%d %H:%M.%S")} (adjusted; estimated)' ) output.append( f'{cwWeekdayNames[int(cwtdt.weekday())]} {cwtdt.strftime("%H:%M.%S")} (tabular)' ) output.append( f'{sunmoon} {cwPeriodNames[int(cwadt.hour/6)]}: next change in ≈{int(timeToPeriodChange/3600)}h {int((timeToPeriodChange%3600)/60)}′ {int(timeToPeriodChange%60)}″' ) output.append( f'⚔ next battle in {int(timeToBattle/3600)}h {int((timeToBattle%3600)/60)}′ {int(timeToBattle%60)}″' ) output.append( f'📯 arena resets in {int(timeToArena/3600)}h {int((timeToArena%3600)/60)}′ {int(timeToArena%60)}″' ) output.append(f'this month: {cwMonthNames[int(cwadt.month)]}') output.append( f'next month: {cwMonthNames[int(cwadt.month)+1]}{"("+str(cwadt.year+1)+")" if cwadt.month == 12 else ""}' ) output.append('') pacificD = 'D' if (utcdt.astimezone(PT).utcoffset().total_seconds() == -25200) else 'S' mountainD = 'D' if (utcdt.astimezone(MT).utcoffset().total_seconds() == -21600) else 'S' centralD = 'D' if (utcdt.astimezone(CT).utcoffset().total_seconds() == -18000) else 'S' easternD = 'D' if (utcdt.astimezone(ET).utcoffset().total_seconds() == -14400) else 'S' europeanS = 'S' if (utcdt.astimezone(CET).utcoffset().total_seconds() == 7200) else '' output.append( f'{utcdt.astimezone(PT).strftime("%A %F %H:%M.%S")} P{pacificD}T (UTC standard)' ) output.append(f" ╰ GMT−{8 - (pacificD == 'D')}: San Francisco, San Diego") output.append(f'{utcdt.astimezone(ET).strftime("%A %H:%M")} E{easternD}T') output.append(f" ╰ GMT−{5 - (easternD == 'D')}: Boston, Augusta, Havana") output.append(f'{utcdt.astimezone(GMT).strftime("%A %H:%M")} GMT') output.append(" ╰ GMT±0: Accra") output.append( f'{utcdt.astimezone(CET).strftime("%A %H:%M")} CE{europeanS}T') output.append(f" ╰ GMT+{1 + (europeanS == 'S')}: Amsterdam, Bern") output.append(f'{utcdt.astimezone(WPS).strftime("%A %H:%M")} WPS') output.append(" ╰ GMT+8: Singapore, Manila, Hong Kong") output.append('') output.append( f"Equivalent dates (in P{pacificD}T; dates change at midnight)") output.append( f'{heb.year} {hebMonthNames[heb.month]}{" I" if hebrewcal.Year(heb.year).leap and heb.month > 11 else ""}{"I" if (hebrewcal.Year(heb.year).leap and heb.month == 13) else ""} {heb.day}' + f' ({hebrew_numeral(heb.day)} {hebMonthNamesIvrit[heb.month]}{(" ב" if heb.month == 13 else " א") if hebrewcal.Year(heb.year).leap and heb.month > 11 else ""} {hebrew_numeral(heb.year)})' ) output.append(f'{yin.year+2698}/{yin.year+2638}年{yin.month}月{yin.day}日') output.append( f'{ses.natural.year:0>5d}.{ses.natural.season:0>1d}.{ses.natural.day:0>2d} (cyclic: {ses.cyclic.great}.{ses.cyclic.small}.{ses.cyclic.year}:{ses.cyclic.season}.{ses.cyclic.week}.{ses.cyclic.day})' ) return '\n'.join(output)