Separate Calendar Logic from Locale Display
Core idea
calendar computes Gregorian calendar layouts and properties. monthrange(year, month) returns the weekday of the first day and the number of days in the month; Monday is zero. Human-readable month and weekday names can depend on LC_TIME and installed locales. Keep numeric interchange formats separate from localized display.
import calendarprint(calendar.monthrange(2024, 2)[1])print(calendar.monthrange(2023, 2)[1])Leap-year rules change the Gregorian month length.
Choose explicit display labels
from datetime import datelabels = ["دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه", "یکشنبه"]d = date(2024, 1, 1)print(d.isoformat(), labels[d.weekday()])This explicit Persian weekday table is independent of host locale; the date remains Gregorian, not Solar Hijri.
Common mistake
locale.setlocale changes process-wide state and may fail if a locale is not installed. Do not switch it for each concurrent request. Translating labels does not convert Gregorian dates to a different calendar system.
Practice
Create a numeric calendar report for February 2024 and 2025, then choose a language-specific weekday label without changing global locale.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Calendar and locale
Check your understanding of calendar and locale.
What is printed?
import calendarprint(calendar.isleap(1900),calendar.isleap(2000))What is printed?
import calendarprint(calendar.weekday(2024,1,1))Why avoid setlocale for each concurrent request?
Does Persian weekday text make a Gregorian date Solar Hijri?