python datetime

เนื่องจากเวลาใช้งาน datetime เป็นเรื่องที่ยุ่งในการ กำหนดให้คนอื่นใช้ตามเรา เลยลองสร้าง class ToDay()
ขึ้นมา เพื่อกำหนดค่า datetime เป็น relative จากวันปัจจุบันหนะครับ ยังไม่เสร็จนะครับแต่ติดปัญหา เลยขอความรู้เกี่ยวกับ class

class ToDay():
    import datetime
    def __init__(self):
        def last_day_of_month(any_day):
            next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
            return next_month - datetime.timedelta(days=next_month.day)
        def get_quarter(any_dt):
            return int((any_dt.month -1 )/3)
        
        self.monthlist = [i for i in range(1,13)]
        self.now = datetime.datetime.now()
        self.today = datetime.datetime.today().date()
        self.beginthismonth = datetime.datetime(self.now.year,self.now.month,1).date()
        self.endthismonth = last_day_of_month(self.today)
        self.beginlastmonth = datetime.datetime(self.now.year, self.now.month-1,1).date()
        self.endlastmonth = self.beginthismonth-datetime.timedelta(days=1)
        # USA quarter (Jan - Mar), (Apr - Jun), (Jul - Sep), (Oct - Dec)
        self.beginthisquarter = get_quarter(self.today)
        # JP quarter (Apr - Jun), (Jul - Sep), (Oct - Dec), (Jan - Mar)
        # Custom quarter (Sep - Nov), (Dec - Feb), (Mar - May), (Jun - Aug)

mydate = ToDay()

print(type(mydate.today), mydate.today)
print(type(mydate.now), mydate.now)
print(type(mydate.beginthismonth), mydate.beginthismonth)
print(type(mydate.endthismonth), mydate.endthismonth)
print(type(mydate.beginlastmonth), mydate.beginlastmonth)
print(type(mydate.endlastmonth), mydate.endlastmonth)
print(type(mydate.beginthisquarter), mydate.beginthisquarter)


ดูเหมือนก็แสดงค่าออกมาใช้งานได้ระดับนึง แต่ตรง quarter ควรเขียนยังไงหนะครับ

# USA quarter (Jan - Mar), (Apr - Jun), (Jul - Sep), (Oct - Dec)
# datetime.datetime.month [1..12]
self.beginthisquarter = get_quarter(self.today)
# JP quarter (Apr - Jun), (Jul - Sep), (Oct - Dec), (Jan - Mar)
# Custom quarter (Sep - Nov), (Dec - Feb), (Mar - May), (Jun - Aug)

เพราะว่า บางทีมันก็ไตรมาสปกติแบบสากล กับบางบริษัทมันก็เป็นแบบ ญี่ปุ่น ที่แตกต่างกว่าสากล

แบบนี้เราจะแก้ class อย่างไรครับหรือควรจะมี def method ย่อย ๆ อีกดีครับ รบกวนขอคำแนะนำ ขอบคุณครับ

สอบถามเพิ่ม พึ่งลองว่า มันถูก ใส่ค่าใหม่ทันได้ด้วย เห้อ

mydate.endthismonth = datetime.datetime(2020,12,31)
print(mydate.beginthismonth, mydate.endthismonth)
ถ้าป้องกันไม่ให้เซ็ตทับ ต้องปรับ class ยังไงครับ?
แก้ไขข้อความเมื่อ
แสดงความคิดเห็น
โปรดศึกษาและยอมรับนโยบายข้อมูลส่วนบุคคลก่อนเริ่มใช้งาน อ่านเพิ่มเติมได้ที่นี่