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
12 from types
import SliceType
14 __all__
= ["error","setfirstweekday","firstweekday","isleap",
15 "leapdays","weekday","monthrange","monthcalendar",
16 "prmonth","month","prcal","calendar","timegm",
17 "month_name", "month_abbr", "day_name", "day_abbr"]
19 # Exception raised for bad input (with string parameter for details)
22 # Constants for months referenced later
26 # Number of days per month (except for February in leap years)
27 mdays
= [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
29 # This module used to have hard-coded lists of day and month names, as
30 # English strings. The classes following emulate a read-only version of
31 # that, but supply localized names. Note that the values are computed
32 # fresh on each call, in case the user changes locale between calls.
35 def __getitem__(self
, i
):
36 if isinstance(i
, SliceType
):
37 return self
.data
[i
.start
: i
.stop
]
39 # May raise an appropriate exception.
42 class _localized_month(_indexer
):
43 def __init__(self
, format
):
46 def __getitem__(self
, i
):
47 self
.data
= [strftime(self
.format
, (2001, j
, 1, 12, 0, 0, 1, 1, 0))
48 for j
in range(1, 13)]
49 self
.data
.insert(0, "")
50 return _indexer
.__getitem
__(self
, i
)
55 class _localized_day(_indexer
):
56 def __init__(self
, format
):
59 def __getitem__(self
, i
):
60 # January 1, 2001, was a Monday.
61 self
.data
= [strftime(self
.format
, (2001, 1, j
+1, 12, 0, 0, j
, j
+1, 0))
63 return _indexer
.__getitem
__(self
, i
)
68 # Full and abbreviated names of weekdays
69 day_name
= _localized_day('%A')
70 day_abbr
= _localized_day('%a')
72 # Full and abbreviated names of months (1-based arrays!!!)
73 month_name
= _localized_month('%B')
74 month_abbr
= _localized_month('%b')
76 # Constants for weekdays
77 (MONDAY
, TUESDAY
, WEDNESDAY
, THURSDAY
, FRIDAY
, SATURDAY
, SUNDAY
) = range(7)
79 _firstweekday
= 0 # 0 = Monday, 6 = Sunday
84 def setfirstweekday(weekday
):
85 """Set weekday (Monday=0, Sunday=6) to start each week."""
87 if not MONDAY
<= weekday
<= SUNDAY
:
89 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
90 _firstweekday
= weekday
93 """Return 1 for leap years, 0 for non-leap years."""
94 return year
% 4 == 0 and (year
% 100 != 0 or year
% 400 == 0)
97 """Return number of leap years in range [y1, y2).
101 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400)
103 def weekday(year
, month
, day
):
104 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
106 secs
= mktime((year
, month
, day
, 0, 0, 0, 0, 0, 0))
107 tuple = localtime(secs
)
110 def monthrange(year
, month
):
111 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
113 if not 1 <= month
<= 12:
114 raise ValueError, 'bad month number'
115 day1
= weekday(year
, month
, 1)
116 ndays
= mdays
[month
] + (month
== February
and isleap(year
))
119 def monthcalendar(year
, month
):
120 """Return a matrix representing a month's calendar.
121 Each row represents a week; days outside this month are zero."""
122 day1
, ndays
= monthrange(year
, month
)
125 day
= (_firstweekday
- day1
+ 6) % 7 - 5 # for leading 0's in first week
127 row
= [0, 0, 0, 0, 0, 0, 0]
129 if 1 <= day
<= ndays
: row
[i
] = day
134 def _center(str, width
):
135 """Center a string in a field."""
139 return ' '*((n
+1)/2) + str + ' '*((n
)/2)
141 def prweek(theweek
, width
):
142 """Print a single week (no newline)."""
143 print week(theweek
, width
),
145 def week(theweek
, width
):
146 """Returns a single week in a string (no newline)."""
152 s
= '%2i' % day
# right-align single-digit days
153 days
.append(_center(s
, width
))
154 return ' '.join(days
)
156 def weekheader(width
):
157 """Return a header for a week."""
163 for i
in range(_firstweekday
, _firstweekday
+ 7):
164 days
.append(_center(names
[i
%7][:width
], width
))
165 return ' '.join(days
)
167 def prmonth(theyear
, themonth
, w
=0, l
=0):
168 """Print a month's calendar."""
169 print month(theyear
, themonth
, w
, l
),
171 def month(theyear
, themonth
, w
=0, l
=0):
172 """Return a month's calendar string (multi-line)."""
175 s
= (_center(month_name
[themonth
] + ' ' + `theyear`
,
176 7 * (w
+ 1) - 1).rstrip() +
177 '\n' * l
+ weekheader(w
).rstrip() + '\n' * l
)
178 for aweek
in monthcalendar(theyear
, themonth
):
179 s
= s
+ week(aweek
, w
).rstrip() + '\n' * l
182 # Spacing of month columns for 3-column year calendar
183 _colwidth
= 7*3 - 1 # Amount printed by prweek()
184 _spacing
= 6 # Number of spaces between columns
186 def format3c(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
187 """Prints 3-column formatting for year calendars"""
188 print format3cstring(a
, b
, c
, colwidth
, spacing
)
190 def format3cstring(a
, b
, c
, colwidth
=_colwidth
, spacing
=_spacing
):
191 """Returns a string formatted from 3 strings, centered within 3 columns."""
192 return (_center(a
, colwidth
) + ' ' * spacing
+ _center(b
, colwidth
) +
193 ' ' * spacing
+ _center(c
, colwidth
))
195 def prcal(year
, w
=0, l
=0, c
=_spacing
):
196 """Print a year's calendar."""
197 print calendar(year
, w
, l
, c
),
199 def calendar(year
, w
=0, l
=0, c
=_spacing
):
200 """Returns a year's calendar as a multi-line string."""
204 colwidth
= (w
+ 1) * 7 - 1
205 s
= _center(`year`
, colwidth
* 3 + c
* 2).rstrip() + '\n' * l
206 header
= weekheader(w
)
207 header
= format3cstring(header
, header
, header
, colwidth
, c
).rstrip()
208 for q
in range(January
, January
+12, 3):
210 format3cstring(month_name
[q
], month_name
[q
+1], month_name
[q
+2],
211 colwidth
, c
).rstrip() +
212 '\n' * l
+ header
+ '\n' * l
)
215 for amonth
in range(q
, q
+ 3):
216 cal
= monthcalendar(year
, amonth
)
217 if len(cal
) > height
:
220 for i
in range(height
):
226 weeks
.append(week(cal
[i
], w
))
227 s
= s
+ format3cstring(weeks
[0], weeks
[1], weeks
[2],
228 colwidth
, c
).rstrip() + '\n' * l
233 """Unrelated but handy function to calculate Unix timestamp from GMT."""
234 year
, month
, day
, hour
, minute
, second
= tuple[:6]
236 assert 1 <= month
<= 12
237 days
= 365*(year
-EPOCH
) + leapdays(EPOCH
, year
)
238 for i
in range(1, month
):
239 days
= days
+ mdays
[i
]
240 if month
> 2 and isleap(year
):
242 days
= days
+ day
- 1
243 hours
= days
*24 + hour
244 minutes
= hours
*60 + minute
245 seconds
= minutes
*60 + second