Exemplo n.º 1
0
    def _populate(self, year):
        # New Year's Day
        name = "New Year's Day"
        self[date(year, 1, 1)] = name

        # New Year's Day by the Lunar
        name = "New Year's Day by the Lunar"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 1)).to_date()
            if ds.year == year:
                self[ds] = name

        # Independence Movement Day
        name = "Independence Movement Day"
        self[date(year, 3, 1)] = name

        # Buddha's Birthday
        name = "Buddha's Birthday"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 4, 8)).to_date()
            if ds.year == year:
                self[ds] = name

        # Children's Day
        name = "Children's Day"
        self[date(year, 5, 5)] = name

        # Memorial Day
        name = "Memorial Day"
        self[date(year, 6, 6)] = name

        # Liberation Day
        name = "Liberation Day"
        self[date(year, 8, 15)] = name

        # Chuseok
        name = "Chuseok"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 8, 15)).to_date()
            if ds.year == year:
                self[ds] = name

        # National Foundation Day
        name = "National Foundation Day"
        self[date(year, 10, 3)] = name

        # Hangeul Proclamation Day
        name = "Hangeul Proclamation Day"
        self[date(year, 10, 9)] = name

        # Christmas Day
        name = "Christmas Day"
        self[date(year, 12, 25)] = name
Exemplo n.º 2
0
 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()
Exemplo n.º 3
0
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
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
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
    })
Exemplo n.º 7
0
    def _populate(self, year):
        # New Year's Day
        name = "New Year's Day"
        self[date(year, 1, 1)] = name

        # Vietnamese New Year
        name = "Vietnamese New Year"
        for offset in range(-1, 2, 1):
            try:
                ds = Converter.Lunar2Solar(Lunar(year - 1 + offset, 12,
                                                 30)).to_date()
            except DateNotExist:
                ds = Converter.Lunar2Solar(Lunar(year - 1 + offset, 12,
                                                 29)).to_date()
            if ds.year == year:
                self[ds] = name
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 1)).to_date()
            if ds.year == year:
                self[ds] = name
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 2)).to_date()
            if ds.year == year:
                self[ds] = name
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 3)).to_date()
            if ds.year == year:
                self[ds] = name
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 4)).to_date()
            if ds.year == year:
                self[ds] = name
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 5)).to_date()
            if ds.year == year:
                self[ds] = name

        # Hung Kings Commemorations
        name = "Hung Kings Commemorations"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 3, 10)).to_date()
            if ds.year == year:
                self[ds] = name

        # Reunification Day
        name = "Reunification Day"
        self[date(year, 4, 30)] = name

        # Labor Day/International Workers' Day
        name = "Labor Day/International Workers' Day"
        self[date(year, 5, 1)] = name

        # National Day
        name = "National Day"
        self[date(year, 9, 2)] = name
Exemplo n.º 8
0
 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)
Exemplo n.º 9
0
    def _populate(self, year):
        # New Year's Day
        name = "New Year's Day"
        self[date(year, 1, 1)] = name

        # Chinese New Year/ Spring Festival
        name = "Chinese New Year"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 1)).to_date()
            if ds.year == year:
                self[ds] = name

        # Tomb-Sweeping Day
        name = "Tomb-Sweeping Day"
        self[date(year, 4, 4)] = name
        self[date(year, 4, 5)] = name

        # Labor Day
        name = "Labor Day"
        self[date(year, 5, 1)] = name

        # Dragon Boat Festival
        name = "Dragon Boat Festival"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 5, 5)).to_date()
            if ds.year == year:
                self[ds] = name

        # Mid-Autumn Festival
        name = "Mid-Autumn Festival"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 8, 15)).to_date()
            if ds.year == year:
                self[ds] = name

        # National Day
        name = "National Day"
        self[date(year, 10, 1)] = name
Exemplo n.º 10
0
 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()
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
    def _populate(self, year):
        # New Year's Day
        if not self.observed and date(year, 1, 1).weekday() in WEEKEND:
            pass
        else:
            self[date(year, 1, 1)] = "New Year's Day"

        # Chinese New Year/ Spring Festival
        name = "Chinese New Year"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 1)).to_date()
            if ds.year == year:
                self[ds] = name

        # Day of Silence / Nyepi
        # Note:
        # This holiday is determined by Balinese calendar, which is not currently
        # available. Only hard coded version of this holiday from 2009 to 2019
        # is available.
        warning_msg = "We only support Nyepi holiday from 2009 to 2019"
        log.warning(warning_msg)

        name = "Day of Silence/ Nyepi"
        if year == 2009:
            self[date(year, 3, 26)] = name
        elif year == 2010:
            self[date(year, 3, 16)] = name
        elif year == 2011:
            self[date(year, 3, 5)] = name
        elif year == 2012:
            self[date(year, 3, 23)] = name
        elif year == 2013:
            self[date(year, 3, 12)] = name
        elif year == 2014:
            self[date(year, 3, 31)] = name
        elif year == 2015:
            self[date(year, 3, 21)] = name
        elif year == 2016:
            self[date(year, 3, 9)] = name
        elif year == 2017:
            self[date(year, 3, 28)] = name
        elif year == 2018:
            self[date(year, 3, 17)] = name
        elif year == 2019:
            self[date(year, 3, 7)] = name
        else:
            pass

        # Ascension of the Prophet
        name = "Ascension of the Prophet"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 3, 17)[0]
            y, m, d = to_gregorian(islam_year, 7, 27)
            if y == year:
                self[date(y, m, d)] = name

        # Labor Day
        name = "Labor Day"
        self[date(year, 5, 1)] = name

        # Ascension of Jesus Christ
        name = "Ascension of Jesus"
        for offset in range(-1, 2, 1):
            ds = easter(year + offset) + rd(days=+39)
            if ds.year == year:
                self[ds] = name

        # Buddha's Birthday
        name = "Buddha's Birthday"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 4, 15)).to_date()
            if ds.year == year:
                self[ds] = name

        # Pancasila Day, since 2017
        if year >= 2017:
            name = "Pancasila Day"
            self[date(year, 6, 1)] = name

        # Eid al-Fitr
        name = "Eid al-Fitr"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 6, 15)[0]
            y1, m1, d1 = to_gregorian(islam_year, 10, 1)
            y2, m2, d2 = to_gregorian(islam_year, 10, 2)
            if y1 == year:
                self[date(y1, m2, d2)] = name
            if y2 == year:
                self[date(y2, m2, d2)] = name

        # Independence Day
        name = "Independence Day"
        self[date(year, 8, 17)] = name

        # Feast of the Sacrifice
        name = "Feast of the Sacrifice"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 8, 22)[0]
            y, m, d = to_gregorian(islam_year, 12, 10)
            if y == year:
                self[date(y, m, d)] = name

        # Islamic New Year
        name = "Islamic New Year"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 9, 11)[0]
            y, m, d = to_gregorian(islam_year + 1, 1, 1)
            if y == year:
                self[date(y, m, d)] = name

        # Birth of the Prophet
        name = "Birth of the Prophet"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 11, 20)[0]
            y, m, d = to_gregorian(islam_year + 1, 3, 12)
            if y == year:
                self[date(y, m, d)] = name

        # Christmas
        self[date(year, 12, 25)] = "Christmas"
Exemplo n.º 13
0
    def _populate(self, year):
        # New Year's Day
        name = "New Year's Day"
        self[date(year, 1, 1)] = name

        # Magha Pujab
        # Note:
        # This holiday is determined by Buddhist calendar, which is not currently
        # available. Only hard coded version of this holiday from 2016 to 2019
        # is available.

        name = "Magha Pujab/Makha Bucha"
        if year == 2016:
            self[date(year, 2, 22)] = name
        elif year == 2017:
            self[date(year, 2, 11)] = name
        elif year == 2018:
            self[date(year, 3, 1)] = name
        elif year == 2019:
            self[date(year, 2, 19)] = name
        else:
            pass

        # Chakri Memorial Day
        name = "Chakri Memorial Day"
        april_6 = date(year, 4, 6).weekday()
        if april_6 == 5:
            self[date(year, 4, 6 + 2)] = name
        elif april_6 == 6:
            self[date(year, 4, 6 + 1)] = name
        else:
            self[date(year, 4, 6)] = name

        # Songkran Festival
        name = "Songkran Festival"
        self[date(year, 4, 14)] = name

        # Royal Ploughing Ceremony
        # arbitrary day in May

        # Buddha's Birthday
        name = "Buddha's Birthday"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 4, 15)).to_date()
            if ds.year == year:
                self[ds] = name

        # Coronation Day, removed in 2017
        name = "Coronation Day"
        if year < 2017:
            self[date(year, 5, 5)] = name

        # King Maha Vajiralongkorn's Birthday
        name = "King Maha Vajiralongkorn's Birthday"
        self[date(year, 7, 28)] = name

        # Asalha Puja
        # This is also a Buddha holiday, and we only implement
        # the hard coded version from 2006 to 2025
        # reference:
        # http://www.when-is.com/asalha_puja.asp
        warning_msg = "We only support Asalha Puja holiday from 2006 to 2025"
        log.warning(warning_msg)
        name = "Asalha Puja"
        if year == 2006:
            self[date(year, 7, 11)] = name
        elif year == 2007:
            self[date(year, 6, 30)] = name
        elif year == 2008:
            self[date(year, 7, 18)] = name
        elif year == 2009:
            self[date(year, 7, 7)] = name
        elif year == 2010:
            self[date(year, 7, 25)] = name
        elif year == 2011:
            self[date(year, 7, 15)] = name
        elif year == 2012:
            self[date(year, 8, 2)] = name
        elif year == 2013:
            self[date(year, 7, 30)] = name
        elif year == 2014:
            self[date(year, 7, 13)] = name
        elif year == 2015:
            self[date(year, 7, 30)] = name
        elif year == 2016:
            self[date(year, 7, 15)] = name
        elif year == 2017:
            self[date(year, 7, 9)] = name
        elif year == 2018:
            self[date(year, 7, 29)] = name
        elif year == 2019:
            self[date(year, 7, 16)] = name
        elif year == 2020:
            self[date(year, 7, 5)] = name
        elif year == 2021:
            self[date(year, 7, 24)] = name
        elif year == 2022:
            self[date(year, 7, 13)] = name
        elif year == 2023:
            self[date(year, 7, 3)] = name
        elif year == 2024:
            self[date(year, 7, 21)] = name
        elif year == 2025:
            self[date(year, 7, 10)] = name
        else:
            pass

        # Beginning of Vassa
        warning_msg = "We only support Vassa holiday from 2006 to 2020"
        log.warning(warning_msg)
        name = "Beginning of Vassa"
        if year == 2006:
            self[date(year, 7, 12)] = name
        elif year == 2007:
            self[date(year, 7, 31)] = name
        elif year == 2008:
            self[date(year, 7, 19)] = name
        elif year == 2009:
            self[date(year, 7, 8)] = name
        elif year == 2010:
            self[date(year, 7, 27)] = name
        elif year == 2011:
            self[date(year, 7, 16)] = name
        elif year == 2012:
            self[date(year, 8, 3)] = name
        elif year == 2013:
            self[date(year, 7, 23)] = name
        elif year == 2014:
            self[date(year, 7, 13)] = name
        elif year == 2015:
            self[date(year, 8, 1)] = name
        elif year == 2016:
            self[date(year, 7, 20)] = name
        elif year == 2017:
            self[date(year, 7, 9)] = name
        elif year == 2018:
            self[date(year, 7, 28)] = name
        elif year == 2019:
            self[date(year, 7, 17)] = name
        elif year == 2020:
            self[date(year, 7, 6)] = name
        else:
            pass

        # The Queen Sirikit's Birthday
        name = "The Queen Sirikit's Birthday"
        self[date(year, 8, 12)] = name

        # Anniversary for the Death of King Bhumibol Adulyadej
        name = "Anniversary for the Death of King Bhumibol Adulyadej"
        self[date(year, 10, 13)] = name

        # King Chulalongkorn Day
        name = "King Chulalongkorn Day"
        self[date(year, 10, 23)] = name

        # King Bhumibol Adulyadej's Birthday Anniversary
        name = "King Bhumibol Adulyadej's Birthday Anniversary"
        self[date(year, 12, 5)] = name

        # Constitution Day
        name = "Constitution Day"
        self[date(year, 12, 10)] = name

        # New Year's Eve
        name = "New Year's Eve"
        self[date(year, 12, 31)] = name
Exemplo n.º 14
0
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')
Exemplo n.º 15
0
    def _populate(self, year):
        # New Year's Day
        name = "New Year's Day"
        self[date(year, 1, 1)] = name

        # Birthday of Prophet, Mawlid in India
        # 12th day of 3rd Islamic month
        name = "Birth of Prophet"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 11, 20)[0]
            y, m, d = to_gregorian(islam_year, 3, 12)
            if y == year:
                self[date(y, m, d)] = name

        # Chinese New Year
        name = "Chinese New Year"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 1)).to_date()
            if ds.year == year:
                self[ds] = name

        # Tamil New Year
        # Note: it's not necessarily 04/14
        # due to the local calendar
        # other possible dates are 04/13 and 04/15
        name = "Tamil New Year"
        self[date(year, 4, 14)] = name

        # Good Friday
        name = "Good Friday"
        for offset in range(-1, 2, 1):
            ds = easter(year + offset) - rd(days=2)
            if ds.year == year:
                self[ds] = name

        # Labor Day
        name = "Labor Day"
        self[date(year, 5, 1)] = name

        # Buddha's Birthday
        name = "Wesak Day"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 4, 15)).to_date()
            if ds.year == year:
                self[ds] = name

        # King's birthday
        # https://www.thestar.com.my/news/nation/2017/04/26/
        # Before 2017: first Saturday of June
        # 2017-2021: last Saturday of July
        name = "King's birthday"
        if year < 2017:
            c = Calendar(firstweekday=MONDAY)
            monthcal = c.monthdatescalendar(year, 6)

            l1 = len(monthcal)
            saturdays = []
            for i in range(l1):
                if monthcal[i][5].month == 6:
                    saturdays.append(monthcal[i][5])
            self[saturdays[0]] = name
        elif (year >= 2017) and (year <= 2021):
            c = Calendar(firstweekday=MONDAY)
            monthcal = c.monthdatescalendar(year, 7)

            l1 = len(monthcal)
            saturdays = []
            for i in range(l1):
                if monthcal[i][5].month == 7:
                    saturdays.append(monthcal[i][5])
            self[saturdays[-1]] = name

        # Eid al-Fitr
        name = "Eid al-Fitr"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 6, 15)[0]
            y1, m1, d1 = to_gregorian(islam_year, 10, 1)
            y2, m2, d2 = to_gregorian(islam_year, 10, 2)
            if y1 == year:
                self[date(y1, m1, d1)] = name
            if y2 == year:
                self[date(y2, m2, d2)] = name

        # Malaysia Day
        name = "Malaysia Day"
        self[date(year, 9, 16)] = name

        # Feast of the Sacrifice
        name = "Feast of the Sacrifice"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 8, 22)[0]
            y, m, d = to_gregorian(islam_year, 12, 10)
            if y == year:
                self[date(y, m, d)] = name

        # First Day of Muharram
        name = "First Day of Muharram"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 9, 11)[0]
            y, m, d = to_gregorian(islam_year + 1, 1, 1)
            if y == year:
                self[date(y, m, d)] = name

        # Christmas
        name = "Christmas Day"
        self[date(year, 12, 25)] = name
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
 def s2l(yy):
     ''' solar date to lunar date '''
     ss = Solar(yy, 2, 10)
     ll = Converter.Solar2Lunar(ss)
     print(f'{ss.to_date()} => {ll}')
Exemplo n.º 18
0
 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
Exemplo n.º 19
0
# -*- 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)