โมดูล calendar ใน Python Standard Library ให้ฟังก์ชันสำหรับจัดการปฏิทิน วันที่ และการคำนวณเกี่ยวกับวัน/สัปดาห์/เดือน/ปี พร้อมรองรับ Locale และ Formatting ต่างๆ
การแสดงปฏิทินทั้งปี
import calendar # พิมพ์ปฏิทินปี 2024 print(calendar.calendar(2024)) # กำหนดความกว้างและระยะห่าง print(calendar.calendar(2024, w=2, l=1, c=6, m=3)) # w=column width, l=lines per week, c=column spacing, m=months per row
การแสดงปฏิทินเดือนเดียว
# July 2024 print(calendar.month(2024, 7)) # July 2024 กำหนดความกว้าง print(calendar.month(2024, 7, w=2, l=1))
ฟังก์ชันสำคัญอื่นๆ
1. monthrange(year, month) - จำนวนวันและวันแรกของเดือน
# February 2024 (Leap Year)
weekday_first, num_days = calendar.monthrange(2024, 2)
print(f"First weekday: {weekday_first} (0=Mon, 6=Sun)") # 3 (Thursday)
print(f"Number of days: {num_days}") # 29
# February 2023 (Non-Leap)
print(calendar.monthrange(2023, 2)) # (2, 28) - Wednesday, 28 days
2. isleap(year) - ตรวจสอบ Leap Year
print(calendar.isleap(2024)) # True print(calendar.isleap(2023)) # False print(calendar.isleap(2000)) # True (Century Leap Year) print(calendar.isleap(1900)) # False (Century not Leap)
3. leapdays(y1, y2) - นับ Leap Years ในช่วง
# Leap years between 2000 and 2024 (2000 <= y < 2024) print(calendar.leapdays(2000, 2024)) # 6 (2000, 2004, 2008, 2012, 2016, 2020)
4. weekday(year, month, day) - หาวันของสัปดาห์
# 0=Monday, 1=Tuesday, ..., 6=Sunday print(calendar.weekday(2024, 1, 1)) # 0 (Monday) print(calendar.weekday(2024, 12, 25)) # 2 (Wednesday) # ชื่อวัน days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] print(days[calendar.weekday(2024, 12, 25)]) # Wed
5. firstweekday() / setfirstweekday()
print(calendar.firstweekday()) # 0 (Monday - Default) # เปลี่ยนเป็น Sunday First (US Style) calendar.setfirstweekday(calendar.SUNDAY) print(calendar.firstweekday()) # 6 # Reset calendar.setfirstweekday(calendar.MONDAY)
6. monthcalendar(year, month) - Matrix ของสัปดาห์ในเดือน
import pprint cal_matrix = calendar.monthcalendar(2024, 2) pprint.pprint(cal_matrix) # [[0, 0, 0, 1, 2, 3, 4], # [5, 6, 7, 8, 9, 10, 11], # [12, 13, 14, 15, 16, 17, 18], # [19, 20, 21, 22, 23, 24, 25], # [26, 27, 28, 29, 0, 0, 0]] # 0 = วันที่ไม่อยู่ในเดือนนั้น
HTML Calendar
import calendar hc = calendar.HTMLCalendar(calendar.MONDAY) html_cal = hc.formatmonth(2024, 3, withyear=True) print(html_cal) # Output:
TextCalendar และ HTMLCalendar Classes
# TextCalendar (Default)
tc = calendar.TextCalendar(firstweekday=calendar.SUNDAY)
print(tc.formatmonth(2024, 1))
# HTMLCalendar
hc = calendar.HTMLCalendar(firstweekday=calendar.SUNDAY)
print(hc.formatmonth(2024, 1))
# Custom CSS Classes
class MyHTMLCal(calendar.HTMLCalendar):
cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
cssclass_noday = "noday"
cssclasses_weekday_head = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
custom_cal = MyHTMLCal()
print(custom_cal.formatmonth(2024, 1))
Locale Support (ภาษาไทย)
import locale
import calendar
# ตั้งค่า Locale (ต้องติดตั้งในระบบ)
try:
locale.setlocale(locale.LC_ALL, 'th_TH.utf8')
cal = calendar.LocaleTextCalendar(locale='th_TH.utf8')
print(cal.formatmonth(2024, 1))
except locale.Error:
print("Thai locale not installed on system")
# Manual Thai Month Names
thai_months = [
'', 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน',
'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
]
def thai_month_calendar(year, month):
import calendar
cal = calendar.TextCalendar()
header = f" {thai_months[month]} {year + 543} " # Buddhist Era
weeks = cal.monthdayscalendar(year, month)
lines = [header, "จันทร์ อังคาร พุธ พฤหัส ศุกร์ เสาร์ อาทิตย์"]
for week in weeks:
line = ' '.join(f"{day:3d}" if day != 0 else " " for day in week)
lines.append(line)
return '\n'.join(lines)
print(thai_month_calendar(2024, 1))
การประยุกต์ใช้งานจริง
1. Business Day Calculator
import calendar
from datetime import date, timedelta
def is_business_day(d):
"""ตรวจสอบว่าเป็นวันทำการ (Mon-Fri)"""
return d.weekday() < 5 # 0-4 = Mon-Fri
def add_business_days(start_date, days):
"""เพิ่ม Business Days"""
current = start_date
added = 0
while added < days:
current += timedelta(days=1)
if is_business_day(current):
added += 1
return current
print(add_business_days(date(2024, 1, 5), 10)) # Skip weekends
2. Generate Date Range for Reporting
def month_date_range(year, month):
"""ได้ Start/End Date ของเดือน"""
_, num_days = calendar.monthrange(year, month)
start = date(year, month, 1)
end = date(year, month, num_days)
return start, end
print(month_date_range(2024, 2)) # (datetime.date(2024, 2, 1), datetime.date(2024, 2, 29))
สรุปฟังก์ชันหลัก
| Function | Description | Returns |
|---|---|---|
calendar(year) | Full Year Calendar | String |
month(year, month) | Single Month Calendar | String |
monthrange(year, month) | First Weekday, Num Days | Tuple (int, int) |
isleap(year) | Check Leap Year | Bool |
leapdays(y1, y2) | Count Leap Years in Range | Int |
weekday(y, m, d) | Day of Week (0=Mon) | Int (0-6) |
monthcalendar(y, m) | Week Matrix | List[List[int]] |
firstweekday() | Get First Weekday Setting | Int (0-6) |
setfirstweekday(day) | Set First Weekday | None |