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
, len):
31 def __getitem__(self
, item
):
32 if isinstance(item
, int):
33 if item
< 0: item
+= self
.len
34 if not 0 <= item
< self
.len:
35 raise IndexError, "out of range"
36 return strftime(self
.format
, (item
,)*9).capitalize()
37 elif isinstance(item
, type(slice(0))):
38 return [self
[e
] for e
in range(self
.len)].__getslice
__(item
.start
, item
.stop
)
42 # Full and abbreviated names of weekdays
43 day_name
= _localized_name('%A', 7)
44 day_abbr
= _localized_name('%a', 7)
46 # Full and abbreviated names of months (1-based arrays!!!)
47 month_name
= _localized_name('%B', 13)
48 month_abbr
= _localized_name('%b', 13)
50 # Constants for weekdays
51 (MONDAY
, TUESDAY
, WEDNESDAY
, THURSDAY
, FRIDAY
, SATURDAY
, SUNDAY
) = range(7)
53 _firstweekday
= 0 # 0 = Monday, 6 = Sunday
58 def setfirstweekday(weekday
):
59 """Set weekday (Monday=0, Sunday=6) to start each week."""
61 if not MONDAY
<= weekday
<= SUNDAY
:
63 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
64 _firstweekday
= weekday
67 """Return 1 for leap years, 0 for non-leap years."""
68 return year
% 4 == 0 and (year
% 100 != 0 or year
% 400 == 0)
71 """Return number of leap years in range [y1, y2).
75 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400)
77 def weekday(year
, month
, day
):
78 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
80 secs
= mktime((year
, month
, day
, 0, 0, 0, 0, 0, 0))
81 tuple = localtime(secs
)
84 def monthrange(year
, month
):
85 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
87 if not 1 <= month
<= 12:
88 raise ValueError, 'bad month number'
89 day1
= weekday(year
, month
, 1)
90 ndays
= mdays
[month
] + (month
== February
and isleap(year
))
93 def monthcalendar(year
, month
):
94 """Return a matrix representing a month's calendar.
95 Each row represents a week; days outside this month are zero."""
96 day1
, ndays
= monthrange(year
, month
)
99 day
= (_firstweekday
- day1
+ 6) % 7 - 5 # for leading 0's in first week
101 row
= [0, 0, 0, 0, 0, 0, 0]
103 if 1 <= day
<= ndays
: row
[i
] = day
108 def _center(str, width
):
109 """Center a string in a field."""
113 return ' '*((n
+1)/2) + str + ' '*((n
)/2)
115 def prweek(theweek
, width
):
116 """Print a single week (no newline)."""
117 print week(theweek
, width
),
119 def week(theweek
, width
):
120 """Returns a single week in a string (no newline)."""
126 s
= '%2i' % day
# right-align single-digit days
127 days
.append(_center(s
, width
))
128 return ' '.join(days
)
130 def weekheader(width
):
131 """Return a header for a week."""
137 for i
in range(_firstweekday
, _firstweekday
+ 7):
138 days
.append(_center(names
[i
%7][:width
], width
))
139 return ' '.join(days
)
141 def prmonth(theyear
, themonth
, w
=0, l
=0):
142 """Print a month's calendar."""
143 print month(theyear
, themonth
, w
, l
),
145 def month(theyear
, themonth
, w
=0, l
=0):
146 """Return a month's calendar string (multi-line)."""
149 s
= (_center(month_name
[themonth
] + ' ' + `theyear`
,
150 7 * (w
+ 1) - 1).rstrip() +
151 '\n' * l
+ weekheader(w
).rstrip() + '\n' * l
)
152 for aweek
in monthcalendar(theyear
, themonth
):
153 s
= s
+ week(aweek
, w
).rstrip() + '\n' * l
156 # Spacing of month columns for 3-column year calendar
157 _colwidth
= 7*3 - 1 # Amount printed by prweek()
158 _spacing
= 6 # Number of spaces between columns
160 def format3c(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
161 """Prints 3-column formatting for year calendars"""
162 print format3cstring(a
, b
, c
, colwidth
, spacing
)
164 def format3cstring(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
165 """Returns a string formatted from 3 strings, centered within 3 columns."""
166 return (_center(a
, colwidth
) + ' ' * spacing
+ _center(b
, colwidth
) +
167 ' ' * spacing
+ _center(c
, colwidth
))
169 def prcal(year
, w
=0, l
=0, c
=_spacing
):
170 """Print a year's calendar."""
171 print calendar(year
, w
, l
, c
),
173 def calendar(year
, w
=0, l
=0, c
=_spacing
):
174 """Returns a year's calendar as a multi-line string."""
178 colwidth
= (w
+ 1) * 7 - 1
179 s
= _center(`year`
, colwidth
* 3 + c
* 2).rstrip() + '\n' * l
180 header
= weekheader(w
)
181 header
= format3cstring(header
, header
, header
, colwidth
, c
).rstrip()
182 for q
in range(January
, January
+12, 3):
184 format3cstring(month_name
[q
], month_name
[q
+1], month_name
[q
+2],
185 colwidth
, c
).rstrip() +
186 '\n' * l
+ header
+ '\n' * l
)
189 for amonth
in range(q
, q
+ 3):
190 cal
= monthcalendar(year
, amonth
)
191 if len(cal
) > height
:
194 for i
in range(height
):
200 weeks
.append(week(cal
[i
], w
))
201 s
= s
+ format3cstring(weeks
[0], weeks
[1], weeks
[2],
202 colwidth
, c
).rstrip() + '\n' * l
207 """Unrelated but handy function to calculate Unix timestamp from GMT."""
208 year
, month
, day
, hour
, minute
, second
= tuple[:6]
210 assert 1 <= month
<= 12
211 days
= 365*(year
-EPOCH
) + leapdays(EPOCH
, year
)
212 for i
in range(1, month
):
213 days
= days
+ mdays
[i
]
214 if month
> 2 and isleap(year
):
216 days
= days
+ day
- 1
217 hours
= days
*24 + hour
218 minutes
= hours
*60 + minute
219 seconds
= minutes
*60 + second