1 """Calendar printing functions
3 Note when comparing these calendars to the ones printed by cal(1): By
4 default, these calendars have Monday as the first day of the week, and
5 Sunday as the last (the European convention). Use setfirstweekday() to
6 set the first day of the week (0=Monday, 6=Sunday)."""
10 __all__
= ["error","setfirstweekday","firstweekday","isleap",
11 "leapdays","weekday","monthrange","monthcalendar",
12 "prmonth","month","prcal","calendar","timegm",
13 "month_name", "month_abbr", "day_name", "day_abbr",
16 # Exception raised for bad input (with string parameter for details)
19 # Constants for months referenced later
23 # Number of days per month (except for February in leap years)
24 mdays
= [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
26 # This module used to have hard-coded lists of day and month names, as
27 # English strings. The classes following emulate a read-only version of
28 # that, but supply localized names. Note that the values are computed
29 # fresh on each call, in case the user changes locale between calls.
31 class _localized_month
:
33 _months
= [datetime
.date(2001, i
+1, 1).strftime
for i
in range(12)]
34 _months
.insert(0, lambda x
: "")
36 def __init__(self
, format
):
39 def __getitem__(self
, i
):
40 funcs
= self
._months
[i
]
41 if isinstance(i
, slice):
42 return [f(self
.format
) for f
in funcs
]
44 return funcs(self
.format
)
51 # January 1, 2001, was a Monday.
52 _days
= [datetime
.date(2001, 1, i
+1).strftime
for i
in range(7)]
54 def __init__(self
, format
):
57 def __getitem__(self
, i
):
59 if isinstance(i
, slice):
60 return [f(self
.format
) for f
in funcs
]
62 return funcs(self
.format
)
67 # Full and abbreviated names of weekdays
68 day_name
= _localized_day('%A')
69 day_abbr
= _localized_day('%a')
71 # Full and abbreviated names of months (1-based arrays!!!)
72 month_name
= _localized_month('%B')
73 month_abbr
= _localized_month('%b')
75 # Constants for weekdays
76 (MONDAY
, TUESDAY
, WEDNESDAY
, THURSDAY
, FRIDAY
, SATURDAY
, SUNDAY
) = range(7)
78 _firstweekday
= 0 # 0 = Monday, 6 = Sunday
83 def setfirstweekday(weekday
):
84 """Set weekday (Monday=0, Sunday=6) to start each week."""
86 if not MONDAY
<= weekday
<= SUNDAY
:
88 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
89 _firstweekday
= weekday
92 """Return 1 for leap years, 0 for non-leap years."""
93 return year
% 4 == 0 and (year
% 100 != 0 or year
% 400 == 0)
96 """Return number of leap years in range [y1, y2).
100 return (y2
//4 - y1
//4) - (y2
//100 - y1
//100) + (y2
//400 - y1
//400)
102 def weekday(year
, month
, day
):
103 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
105 return datetime
.date(year
, month
, day
).weekday()
107 def monthrange(year
, month
):
108 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
110 if not 1 <= month
<= 12:
111 raise ValueError, 'bad month number'
112 day1
= weekday(year
, month
, 1)
113 ndays
= mdays
[month
] + (month
== February
and isleap(year
))
116 def monthcalendar(year
, month
):
117 """Return a matrix representing a month's calendar.
118 Each row represents a week; days outside this month are zero."""
119 day1
, ndays
= monthrange(year
, month
)
122 day
= (_firstweekday
- day1
+ 6) % 7 - 5 # for leading 0's in first week
124 row
= [0, 0, 0, 0, 0, 0, 0]
126 if 1 <= day
<= ndays
: row
[i
] = day
131 def prweek(theweek
, width
):
132 """Print a single week (no newline)."""
133 print week(theweek
, width
),
135 def week(theweek
, width
):
136 """Returns a single week in a string (no newline)."""
142 s
= '%2i' % day
# right-align single-digit days
143 days
.append(s
.center(width
))
144 return ' '.join(days
)
146 def weekheader(width
):
147 """Return a header for a week."""
153 for i
in range(_firstweekday
, _firstweekday
+ 7):
154 days
.append(names
[i
%7][:width
].center(width
))
155 return ' '.join(days
)
157 def prmonth(theyear
, themonth
, w
=0, l
=0):
158 """Print a month's calendar."""
159 print month(theyear
, themonth
, w
, l
),
161 def month(theyear
, themonth
, w
=0, l
=0):
162 """Return a month's calendar string (multi-line)."""
165 s
= ("%s %r" % (month_name
[themonth
], theyear
)).center(
166 7 * (w
+ 1) - 1).rstrip() + \
167 '\n' * l
+ weekheader(w
).rstrip() + '\n' * l
168 for aweek
in monthcalendar(theyear
, themonth
):
169 s
= s
+ week(aweek
, w
).rstrip() + '\n' * l
172 # Spacing of month columns for 3-column year calendar
173 _colwidth
= 7*3 - 1 # Amount printed by prweek()
174 _spacing
= 6 # Number of spaces between columns
176 def format3c(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
177 """Prints 3-column formatting for year calendars"""
178 print format3cstring(a
, b
, c
, colwidth
, spacing
)
180 def format3cstring(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
181 """Returns a string formatted from 3 strings, centered within 3 columns."""
182 return (a
.center(colwidth
) + ' ' * spacing
+ b
.center(colwidth
) +
183 ' ' * spacing
+ c
.center(colwidth
))
185 def prcal(year
, w
=0, l
=0, c
=_spacing
):
186 """Print a year's calendar."""
187 print calendar(year
, w
, l
, c
),
189 def calendar(year
, w
=0, l
=0, c
=_spacing
):
190 """Returns a year's calendar as a multi-line string."""
194 colwidth
= (w
+ 1) * 7 - 1
195 s
= repr(year
).center(colwidth
* 3 + c
* 2).rstrip() + '\n' * l
196 header
= weekheader(w
)
197 header
= format3cstring(header
, header
, header
, colwidth
, c
).rstrip()
198 for q
in range(January
, January
+12, 3):
200 format3cstring(month_name
[q
], month_name
[q
+1], month_name
[q
+2],
201 colwidth
, c
).rstrip() +
202 '\n' * l
+ header
+ '\n' * l
)
205 for amonth
in range(q
, q
+ 3):
206 cal
= monthcalendar(year
, amonth
)
207 if len(cal
) > height
:
210 for i
in range(height
):
216 weeks
.append(week(cal
[i
], w
))
217 s
= s
+ format3cstring(weeks
[0], weeks
[1], weeks
[2],
218 colwidth
, c
).rstrip() + '\n' * l
222 _EPOCH_ORD
= datetime
.date(EPOCH
, 1, 1).toordinal()
225 """Unrelated but handy function to calculate Unix timestamp from GMT."""
226 year
, month
, day
, hour
, minute
, second
= tuple[:6]
227 days
= datetime
.date(year
, month
, 1).toordinal() - _EPOCH_ORD
+ day
- 1
228 hours
= days
*24 + hour
229 minutes
= hours
*60 + minute
230 seconds
= minutes
*60 + second