Python中的日历类型

vuv7lop3  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(118)

我必须Map一定数量的日子,比如说10590到几个不同的日历类型,最好是在python中。
我想使用的日历是标准的,proleptic gregorian,360天,365天,和366天。
我试着在python calendar模块中寻找这样的功能,但没有找到任何东西,至少不是一个直接的解决方案。这是存在的,还是我必须自己实现?
需要说明的是,我不需要显示任何花哨的东西,只需要将给定的一天Map到给定日历类型的日期。
谢谢大家!

k2arahey

k2arahey1#

希望这个替代代码片段可以帮助你。而是使用datetime。当地测试:

import datetime

class Calendar:
    def __init__(self, start_year, start_month, start_day):
        self.start_date = datetime.date(start_year, start_month, start_day)

    def days_to_date(self, days):
        raise NotImplementedError

class GregorianCalendar(Calendar):
    def __init__(self):
        super().__init__(1900, 1, 1)

    def days_to_date(self, days):
        return self.start_date + datetime.timedelta(days=days)

class ProlepticGregorianCalendar(Calendar):
    def __init__(self):
        super().__init__(1, 1, 1)

    def days_to_date(self, days):
        return self.start_date + datetime.timedelta(days=days)

class ThreeSixtyDayCalendar(Calendar):
    def __init__(self):
        super().__init__(1900, 1, 1)

    def days_to_date(self, days):
        years, days_in_year = divmod(days, 360)
        target_year = self.start_date.year + years
        target_month, target_day = divmod(days_in_year, 30)
        return datetime.date(target_year, target_month + 1, target_day + 1)

class ThreeSixtyFiveDayCalendar(Calendar):
    def __init__(self):
        super().__init__(1, 1, 1)

    def days_to_date(self, days):
        return self.start_date + datetime.timedelta(days=days - 1)

class ThreeSixtySixDayCalendar(Calendar):
    def __init__(self):
        super().__init__(1, 1, 1)

    def days_to_date(self, days):
        return self.start_date + datetime.timedelta(days=days - 1)

class CalendarFactory:
    @staticmethod
    def create_calendar(calendar_type):
        if calendar_type == 'gregorian':
            return GregorianCalendar()
        elif calendar_type == 'proleptic_gregorian':
            return ProlepticGregorianCalendar()
        elif calendar_type == '360_day':
            return ThreeSixtyDayCalendar()
        elif calendar_type == '365_day':
            return ThreeSixtyFiveDayCalendar()
        elif calendar_type == '366_day':
            return ThreeSixtySixDayCalendar()
        else:
            raise ValueError('Invalid calendar type')

days = 10590

# create Gregorian calendar and map days to date
calendar = CalendarFactory.create_calendar('gregorian')
print(calendar.days_to_date(days))  # prints: 1931-06-26

# create 360-day calendar and map days to date
calendar = CalendarFactory.create_calendar('360_day')
print(calendar.days_to_date(days))  # prints: 1930-10-29

相关问题