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)."""
8 # Revision 2: uses functions from built-in time module
10 # Import functions and variables from time module
11 from time
import localtime
, mktime
, strftime
13 __all__
= ["error","setfirstweekday","firstweekday","isleap",
14 "leapdays","weekday","monthrange","monthcalendar",
15 "prmonth","month","prcal","calendar","timegm"]
17 # Exception raised for bad input (with string parameter for details)
20 # Constants for months referenced later
24 # Number of days per month (except for February in leap years)
25 mdays
= [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
27 class _localized_name
:
28 def __init__(self
, format
):
30 def __getitem__(self
, item
):
31 return strftime(self
.format
, (item
,)*9).capitalize()
33 # Full and abbreviated names of weekdays
34 day_name
= _localized_name('%A')
35 day_abbr
= _localized_name('%a')
37 # Full and abbreviated names of months (1-based arrays!!!)
38 month_name
= _localized_name('%B')
39 month_abbr
= _localized_name('%b')
41 # Constants for weekdays
42 (MONDAY
, TUESDAY
, WEDNESDAY
, THURSDAY
, FRIDAY
, SATURDAY
, SUNDAY
) = range(7)
44 _firstweekday
= 0 # 0 = Monday, 6 = Sunday
49 def setfirstweekday(weekday
):
50 """Set weekday (Monday=0, Sunday=6) to start each week."""
52 if not MONDAY
<= weekday
<= SUNDAY
:
54 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
55 _firstweekday
= weekday
58 """Return 1 for leap years, 0 for non-leap years."""
59 return year
% 4 == 0 and (year
% 100 != 0 or year
% 400 == 0)
62 """Return number of leap years in range [y1, y2).
66 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400)
68 def weekday(year
, month
, day
):
69 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
71 secs
= mktime((year
, month
, day
, 0, 0, 0, 0, 0, 0))
72 tuple = localtime(secs
)
75 def monthrange(year
, month
):
76 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
78 if not 1 <= month
<= 12:
79 raise ValueError, 'bad month number'
80 day1
= weekday(year
, month
, 1)
81 ndays
= mdays
[month
] + (month
== February
and isleap(year
))
84 def monthcalendar(year
, month
):
85 """Return a matrix representing a month's calendar.
86 Each row represents a week; days outside this month are zero."""
87 day1
, ndays
= monthrange(year
, month
)
90 day
= (_firstweekday
- day1
+ 6) % 7 - 5 # for leading 0's in first week
92 row
= [0, 0, 0, 0, 0, 0, 0]
94 if 1 <= day
<= ndays
: row
[i
] = day
99 def _center(str, width
):
100 """Center a string in a field."""
104 return ' '*((n
+1)/2) + str + ' '*((n
)/2)
106 def prweek(theweek
, width
):
107 """Print a single week (no newline)."""
108 print week(theweek
, width
),
110 def week(theweek
, width
):
111 """Returns a single week in a string (no newline)."""
117 s
= '%2i' % day
# right-align single-digit days
118 days
.append(_center(s
, width
))
119 return ' '.join(days
)
121 def weekheader(width
):
122 """Return a header for a week."""
128 for i
in range(_firstweekday
, _firstweekday
+ 7):
129 days
.append(_center(names
[i
%7][:width
], width
))
130 return ' '.join(days
)
132 def prmonth(theyear
, themonth
, w
=0, l
=0):
133 """Print a month's calendar."""
134 print month(theyear
, themonth
, w
, l
),
136 def month(theyear
, themonth
, w
=0, l
=0):
137 """Return a month's calendar string (multi-line)."""
140 s
= (_center(month_name
[themonth
] + ' ' + `theyear`
,
141 7 * (w
+ 1) - 1).rstrip() +
142 '\n' * l
+ weekheader(w
).rstrip() + '\n' * l
)
143 for aweek
in monthcalendar(theyear
, themonth
):
144 s
= s
+ week(aweek
, w
).rstrip() + '\n' * l
147 # Spacing of month columns for 3-column year calendar
148 _colwidth
= 7*3 - 1 # Amount printed by prweek()
149 _spacing
= 6 # Number of spaces between columns
151 def format3c(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
152 """Prints 3-column formatting for year calendars"""
153 print format3cstring(a
, b
, c
, colwidth
, spacing
)
155 def format3cstring(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
156 """Returns a string formatted from 3 strings, centered within 3 columns."""
157 return (_center(a
, colwidth
) + ' ' * spacing
+ _center(b
, colwidth
) +
158 ' ' * spacing
+ _center(c
, colwidth
))
160 def prcal(year
, w
=0, l
=0, c
=_spacing
):
161 """Print a year's calendar."""
162 print calendar(year
, w
, l
, c
),
164 def calendar(year
, w
=0, l
=0, c
=_spacing
):
165 """Returns a year's calendar as a multi-line string."""
169 colwidth
= (w
+ 1) * 7 - 1
170 s
= _center(`year`
, colwidth
* 3 + c
* 2).rstrip() + '\n' * l
171 header
= weekheader(w
)
172 header
= format3cstring(header
, header
, header
, colwidth
, c
).rstrip()
173 for q
in range(January
, January
+12, 3):
175 format3cstring(month_name
[q
], month_name
[q
+1], month_name
[q
+2],
176 colwidth
, c
).rstrip() +
177 '\n' * l
+ header
+ '\n' * l
)
180 for amonth
in range(q
, q
+ 3):
181 cal
= monthcalendar(year
, amonth
)
182 if len(cal
) > height
:
185 for i
in range(height
):
191 weeks
.append(week(cal
[i
], w
))
192 s
= s
+ format3cstring(weeks
[0], weeks
[1], weeks
[2],
193 colwidth
, c
).rstrip() + '\n' * l
198 """Unrelated but handy function to calculate Unix timestamp from GMT."""
199 year
, month
, day
, hour
, minute
, second
= tuple[:6]
201 assert 1 <= month
<= 12
202 days
= 365*(year
-EPOCH
) + leapdays(EPOCH
, year
)
203 for i
in range(1, month
):
204 days
= days
+ mdays
[i
]
205 if month
> 2 and isleap(year
):
207 days
= days
+ day
- 1
208 hours
= days
*24 + hour
209 minutes
= hours
*60 + minute
210 seconds
= minutes
*60 + second