Debian Codegraph @

Doc/library/calendar.rst

raw
1 :mod:`!calendar` --- General calendar-related functions
2 =======================================================
3
4 .. module:: calendar
5 :synopsis: Functions for working with calendars, including some emulation
6 of the Unix cal program.
7
8 .. sectionauthor:: Drew Csillag <[email protected]>
9
10 **Source code:** :source:`Lib/calendar.py`
11
12 --------------
13
14 This module allows you to output calendars like the Unix :program:`cal` program,
15 and provides additional useful functions related to the calendar. By default,
16 these calendars have Monday as the first day of the week, and Sunday as the last
17 (the European convention). Use :func:`setfirstweekday` to set the first day of
18 the week to Sunday (6) or to any other weekday. Parameters that specify dates
19 are given as integers. For related
20 functionality, see also the :mod:`datetime` and :mod:`time` modules.
21
22 The functions and classes defined in this module
23 use an idealized calendar, the current Gregorian calendar extended indefinitely
24 in both directions. This matches the definition of the "proleptic Gregorian"
25 calendar in Dershowitz and Reingold's book "Calendrical Calculations", where
26 it's the base calendar for all computations. Zero and negative years are
27 interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is
28 2 BC, and so on.
29
30
31 .. class:: Calendar(firstweekday=0)
32
33 Creates a :class:`Calendar` object. *firstweekday* is an integer specifying the
34 first day of the week. :const:`MONDAY` is ``0`` (the default), :const:`SUNDAY` is ``6``.
35
36 A :class:`Calendar` object provides several methods that can be used for
37 preparing the calendar data for formatting. This class doesn't do any formatting
38 itself. This is the job of subclasses.
39
40
41 :class:`Calendar` instances have the following methods and attributes:
42
43 .. attribute:: firstweekday
44
45 The first weekday as an integer (0--6).
46
47 This property can also be set and read using
48 :meth:`~Calendar.setfirstweekday` and
49 :meth:`~Calendar.getfirstweekday` respectively.
50
51 .. method:: getfirstweekday()
52
53 Return an :class:`int` for the current first weekday (0--6).
54
55 Identical to reading the :attr:`~Calendar.firstweekday` property.
56
57 .. method:: setfirstweekday(firstweekday)
58
59 Set the first weekday to *firstweekday*, passed as an :class:`int` (0--6).
60
61 Identical to setting the :attr:`~Calendar.firstweekday` property.
62
63 .. method:: iterweekdays()
64
65 Return an iterator for the weekday numbers that will be used for one
66 week. The first value from the iterator will be the same as the value of
67 the :attr:`~Calendar.firstweekday` property.
68
69
70 .. method:: itermonthdates(year, month)
71
72 Return an iterator for the month *month* (1--12) in the year *year*. This
73 iterator will return all days (as :class:`datetime.date` objects) for the
74 month and all days before the start of the month or after the end of the
75 month that are required to get a complete week.
76
77
78 .. method:: itermonthdays(year, month)
79
80 Return an iterator for the month *month* in the year *year* similar to
81 :meth:`itermonthdates`, but not restricted by the :class:`datetime.date`
82 range. Days returned will simply be day of the month numbers. For the
83 days outside of the specified month, the day number is ``0``.
84
85
86 .. method:: itermonthdays2(year, month)
87
88 Return an iterator for the month *month* in the year *year* similar to
89 :meth:`itermonthdates`, but not restricted by the :class:`datetime.date`
90 range. Days returned will be tuples consisting of a day of the month
91 number and a weekday number.
92
93
94 .. method:: itermonthdays3(year, month)
95
96 Return an iterator for the month *month* in the year *year* similar to
97 :meth:`itermonthdates`, but not restricted by the :class:`datetime.date`
98 range. Days returned will be tuples consisting of a year, a month and a day
99 of the month numbers.
100
101 .. versionadded:: 3.7
102
103
104 .. method:: itermonthdays4(year, month)
105
106 Return an iterator for the month *month* in the year *year* similar to
107 :meth:`itermonthdates`, but not restricted by the :class:`datetime.date`
108 range. Days returned will be tuples consisting of a year, a month, a day
109 of the month, and a day of the week numbers.
110
111 .. versionadded:: 3.7
112
113
114 .. method:: monthdatescalendar(year, month)
115
116 Return a list of the weeks in the month *month* of the *year* as full
117 weeks. Weeks are lists of seven :class:`datetime.date` objects.
118
119
120 .. method:: monthdays2calendar(year, month)
121
122 Return a list of the weeks in the month *month* of the *year* as full
123 weeks. Weeks are lists of seven tuples of day numbers and weekday
124 numbers.
125
126
127 .. method:: monthdayscalendar(year, month)
128
129 Return a list of the weeks in the month *month* of the *year* as full
130 weeks. Weeks are lists of seven day numbers.
131
132
133 .. method:: yeardatescalendar(year, width=3)
134
135 Return the data for the specified year ready for formatting. The return
136 value is a list of month rows. Each month row contains up to *width*
137 months (defaulting to 3). Each month contains between 4 and 6 weeks and
138 each week contains 1--7 days. Days are :class:`datetime.date` objects.
139
140
141 .. method:: yeardays2calendar(year, width=3)
142
143 Return the data for the specified year ready for formatting (similar to
144 :meth:`yeardatescalendar`). Entries in the week lists are tuples of day
145 numbers and weekday numbers. Day numbers outside this month are zero.
146
147
148 .. method:: yeardayscalendar(year, width=3)
149
150 Return the data for the specified year ready for formatting (similar to
151 :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day
152 numbers outside this month are zero.
153
154
155 .. class:: TextCalendar(firstweekday=0)
156
157 This class can be used to generate plain text calendars.
158
159 :class:`TextCalendar` instances have the following methods:
160
161
162 .. method:: formatday(theday, weekday, width)
163
164 Return a string representing a single day formatted with the given *width*.
165 If *theday* is ``0``, return a string of spaces of
166 the specified width, representing an empty day. The *weekday* parameter
167 is unused.
168
169 .. method:: formatweek(theweek, w=0)
170
171 Return a single week in a string with no newline. If *w* is provided, it
172 specifies the width of the date columns, which are centered. Depends
173 on the first weekday as specified in the constructor or set by the
174 :meth:`setfirstweekday` method.
175
176 .. method:: formatweekday(weekday, width)
177
178 Return a string representing the name of a single weekday formatted to
179 the specified *width*. The *weekday* parameter is an integer representing
180 the day of the week, where ``0`` is Monday and ``6`` is Sunday.
181
182 .. method:: formatweekheader(width)
183
184 Return a string containing the header row of weekday names, formatted
185 with the given *width* for each column. The names depend on the locale
186 settings and are padded to the specified width.
187
188 .. method:: formatmonth(theyear, themonth, w=0, l=0)
189
190 Return a month's calendar in a multi-line string. If *w* is provided, it
191 specifies the width of the date columns, which are centered. If *l* is
192 given, it specifies the number of lines that each week will use. Depends
193 on the first weekday as specified in the constructor or set by the
194 :meth:`setfirstweekday` method.
195
196 .. method:: formatmonthname(theyear, themonth, width=0, withyear=True)
197
198 Return a string representing the month's name centered within the
199 specified *width*. If *withyear* is ``True``, include the year in the
200 output. The *theyear* and *themonth* parameters specify the year
201 and month for the name to be formatted respectively.
202
203 .. method:: prmonth(theyear, themonth, w=0, l=0)
204
205 Print a month's calendar as returned by :meth:`formatmonth`.
206
207
208 .. method:: formatyear(theyear, w=2, l=1, c=6, m=3)
209
210 Return a *m*-column calendar for an entire year as a multi-line string.
211 Optional parameters *w*, *l*, and *c* are for date column width, lines per
212 week, and number of spaces between month columns, respectively. Depends on
213 the first weekday as specified in the constructor or set by the
214 :meth:`setfirstweekday` method. The earliest year for which a calendar
215 can be generated is platform-dependent.
216
217
218 .. method:: pryear(theyear, w=2, l=1, c=6, m=3)
219
220 Print the calendar for an entire year as returned by :meth:`formatyear`.
221
222
223 .. class:: HTMLCalendar(firstweekday=0)
224
225 This class can be used to generate HTML calendars.
226
227
228 :class:`!HTMLCalendar` instances have the following methods:
229
230 .. method:: formatmonth(theyear, themonth, withyear=True)
231
232 Return a month's calendar as an HTML table. If *withyear* is true the year
233 will be included in the header, otherwise just the month name will be
234 used.
235
236
237 .. method:: formatyear(theyear, width=3)
238
239 Return a year's calendar as an HTML table. *width* (defaulting to 3)
240 specifies the number of months per row.
241
242
243 .. method:: formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
244
245 Return a year's calendar as a complete HTML page. *width* (defaulting to
246 3) specifies the number of months per row. *css* is the name for the
247 cascading style sheet to be used. :const:`None` can be passed if no style
248 sheet should be used. *encoding* specifies the encoding to be used for the
249 output (defaulting to the system default encoding).
250
251
252 .. method:: formatmonthname(theyear, themonth, withyear=True)
253
254 Return a month name as an HTML table row. If *withyear* is true the year
255 will be included in the row, otherwise just the month name will be
256 used.
257
258
259 :class:`!HTMLCalendar` has the following attributes you can override to
260 customize the CSS classes used by the calendar:
261
262 .. attribute:: cssclasses
263
264 A list of CSS classes used for each weekday. The default class list is::
265
266 cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
267
268 more styles can be added for each day::
269
270 cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
271
272 Note that the length of this list must be seven items.
273
274
275 .. attribute:: cssclass_noday
276
277 The CSS class for a weekday occurring in the previous or coming month.
278
279 .. versionadded:: 3.7
280
281
282 .. attribute:: cssclasses_weekday_head
283
284 A list of CSS classes used for weekday names in the header row.
285 The default is the same as :attr:`cssclasses`.
286
287 .. versionadded:: 3.7
288
289
290 .. attribute:: cssclass_month_head
291
292 The month's head CSS class (used by :meth:`formatmonthname`).
293 The default value is ``"month"``.
294
295 .. versionadded:: 3.7
296
297
298 .. attribute:: cssclass_month
299
300 The CSS class for the whole month's table (used by :meth:`formatmonth`).
301 The default value is ``"month"``.
302
303 .. versionadded:: 3.7
304
305
306 .. attribute:: cssclass_year
307
308 The CSS class for the whole year's table of tables (used by
309 :meth:`formatyear`). The default value is ``"year"``.
310
311 .. versionadded:: 3.7
312
313
314 .. attribute:: cssclass_year_head
315
316 The CSS class for the table head for the whole year (used by
317 :meth:`formatyear`). The default value is ``"year"``.
318
319 .. versionadded:: 3.7
320
321
322 Note that although the naming for the above described class attributes is
323 singular (e.g. ``cssclass_month`` ``cssclass_noday``), one can replace the
324 single CSS class with a space separated list of CSS classes, for example::
325
326 "text-bold text-red"
327
328 Here is an example how :class:`!HTMLCalendar` can be customized::
329
330 class CustomHTMLCal(calendar.HTMLCalendar):
331 cssclasses = [style + " text-nowrap" for style in
332 calendar.HTMLCalendar.cssclasses]
333 cssclass_month_head = "text-center month-head"
334 cssclass_month = "text-center month"
335 cssclass_year = "text-italic lead"
336
337
338 .. class:: LocaleTextCalendar(firstweekday=0, locale=None)
339
340 This subclass of :class:`TextCalendar` can be passed a locale name in the
341 constructor and will return month and weekday names in the specified locale.
342
343
344 .. class:: LocaleHTMLCalendar(firstweekday=0, locale=None)
345
346 This subclass of :class:`HTMLCalendar` can be passed a locale name in the
347 constructor and will return month and weekday names in the specified
348 locale.
349
350 .. note::
351
352 The constructor, :meth:`!formatweekday` and :meth:`!formatmonthname` methods
353 of these two classes temporarily change the ``LC_TIME`` locale to the given
354 *locale*. Because the current locale is a process-wide setting, they are
355 not thread-safe.
356
357
358 For simple text calendars this module provides the following functions.
359
360 .. function:: setfirstweekday(firstweekday)
361
362 Sets the weekday (``0`` is Monday, ``6`` is Sunday) to start each week. The
363 values :const:`MONDAY`, :const:`TUESDAY`, :const:`WEDNESDAY`, :const:`THURSDAY`,
364 :const:`FRIDAY`, :const:`SATURDAY`, and :const:`SUNDAY` are provided for
365 convenience. For example, to set the first weekday to Sunday::
366
367 import calendar
368 calendar.setfirstweekday(calendar.SUNDAY)
369
370
371 .. function:: firstweekday()
372
373 Returns the current setting for the weekday to start each week.
374
375
376 .. function:: isleap(year)
377
378 Returns :const:`True` if *year* is a leap year, otherwise :const:`False`.
379
380
381 .. function:: leapdays(y1, y2)
382
383 Returns the number of leap years in the range from *y1* to *y2* (exclusive),
384 where *y1* and *y2* are years.
385
386 This function works for ranges spanning a century change.
387
388
389 .. function:: weekday(year, month, day)
390
391 Returns the day of the week (``0`` is Monday) for *year* (``1970``--...),
392 *month* (``1``--``12``), *day* (``1``--``31``).
393
394
395 .. function:: weekheader(width)
396
397 Return a header containing abbreviated weekday names. *width* specifies the width in
398 characters for one weekday.
399
400
401 .. function:: monthrange(year, month)
402
403 Returns weekday of first day of the month and number of days in month, for the
404 specified *year* and *month*.
405
406
407 .. function:: monthcalendar(year, month)
408
409 Returns a matrix representing a month's calendar. Each row represents a week;
410 days outside of the month are represented by zeros. Each week begins with Monday
411 unless set by :func:`setfirstweekday`.
412
413
414 .. function:: prmonth(theyear, themonth, w=0, l=0)
415
416 Prints a month's calendar as returned by :func:`month`.
417
418
419 .. function:: month(theyear, themonth, w=0, l=0)
420
421 Returns a month's calendar in a multi-line string using the :meth:`~TextCalendar.formatmonth`
422 of the :class:`TextCalendar` class.
423
424
425 .. function:: prcal(theyear, w=0, l=0, c=6, m=3)
426
427 Prints the calendar for an entire year as returned by :func:`calendar`.
428
429
430 .. function:: calendar(theyear, w=2, l=1, c=6, m=3)
431
432 Returns a 3-column calendar for an entire year as a multi-line string using
433 the :meth:`~TextCalendar.formatyear` of the :class:`TextCalendar` class.
434
435
436 .. function:: timegm(tuple)
437
438 An unrelated but handy function that takes a time tuple such as returned by
439 the :func:`~time.gmtime` function in the :mod:`time` module, and returns the
440 corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX
441 encoding. In fact, :func:`time.gmtime` and :func:`timegm` are each other's
442 inverse.
443
444
445 The :mod:`calendar` module exports the following data attributes:
446
447 .. data:: day_name
448
449 A sequence that represents the days of the week in the current locale,
450 where Monday is day number 0.
451
452 >>> import calendar
453 >>> list(calendar.day_name)
454 ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
455
456
457 .. data:: day_abbr
458
459 A sequence that represents the abbreviated days of the week in the current locale,
460 where Mon is day number 0.
461
462 >>> import calendar
463 >>> list(calendar.day_abbr)
464 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
465
466 .. data:: MONDAY
467 TUESDAY
468 WEDNESDAY
469 THURSDAY
470 FRIDAY
471 SATURDAY
472 SUNDAY
473
474 Aliases for the days of the week,
475 where ``MONDAY`` is ``0`` and ``SUNDAY`` is ``6``.
476
477 .. versionadded:: 3.12
478
479
480 .. class:: Day
481
482 Enumeration defining days of the week as integer constants.
483 The members of this enumeration are exported to the module scope as
484 :data:`MONDAY` through :data:`SUNDAY`.
485
486 .. versionadded:: 3.12
487
488
489 .. data:: month_name
490
491 A sequence that represents the months of the year in the current locale. This
492 follows normal convention of January being month number 1, so it has a length of
493 13 and ``month_name[0]`` is the empty string.
494
495 >>> import calendar
496 >>> list(calendar.month_name)
497 ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
498
499
500 .. data:: month_abbr
501
502 A sequence that represents the abbreviated months of the year in the current
503 locale. This follows normal convention of January being month number 1, so it
504 has a length of 13 and ``month_abbr[0]`` is the empty string.
505
506 >>> import calendar
507 >>> list(calendar.month_abbr)
508 ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
509
510 .. data:: JANUARY
511 FEBRUARY
512 MARCH
513 APRIL
514 MAY
515 JUNE
516 JULY
517 AUGUST
518 SEPTEMBER
519 OCTOBER
520 NOVEMBER
521 DECEMBER
522
523 Aliases for the months of the year,
524 where ``JANUARY`` is ``1`` and ``DECEMBER`` is ``12``.
525
526 .. versionadded:: 3.12
527
528
529 .. class:: Month
530
531 Enumeration defining months of the year as integer constants.
532 The members of this enumeration are exported to the module scope as
533 :data:`JANUARY` through :data:`DECEMBER`.
534
535 .. versionadded:: 3.12
536
537
538 The :mod:`calendar` module defines the following exceptions:
539
540 .. exception:: IllegalMonthError(month)
541
542 A subclass of :exc:`ValueError` and :exc:`IndexError`,
543 raised when the given month number is outside of the range 1-12 (inclusive).
544
545 .. versionchanged:: 3.12
546 :exc:`IllegalMonthError` is now also a subclass of
547 :exc:`ValueError`. New code should avoid catching
548 :exc:`IndexError`.
549
550 .. attribute:: month
551
552 The invalid month number.
553
554
555 .. exception:: IllegalWeekdayError(weekday)
556
557 A subclass of :exc:`ValueError`,
558 raised when the given weekday number is outside of the range 0-6 (inclusive).
559
560 .. attribute:: weekday
561
562 The invalid weekday number.
563
564
565 .. seealso::
566
567 Module :mod:`datetime`
568 Object-oriented interface to dates and times with similar functionality to the
569 :mod:`time` module.
570
571 Module :mod:`time`
572 Low-level time related functions.
573
574
575 .. _calendar-cli:
576
577 Command-Line Usage
578 ------------------
579
580 .. versionadded:: 2.5
581
582 The :mod:`calendar` module can be executed as a script from the command line
583 to interactively print a calendar.
584
585 .. code-block:: shell
586
587 python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]
588 [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]
589 [-f FIRST_WEEKDAY] [year] [month]
590
591
592 For example, to print a calendar for the year 2000:
593
594 .. code-block:: console
595
596 $ python -m calendar 2000
597 2000
598
599 January February March
600 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
601 1 2 1 2 3 4 5 6 1 2 3 4 5
602 3 4 5 6 7 8 9 7 8 9 10 11 12 13 6 7 8 9 10 11 12
603 10 11 12 13 14 15 16 14 15 16 17 18 19 20 13 14 15 16 17 18 19
604 17 18 19 20 21 22 23 21 22 23 24 25 26 27 20 21 22 23 24 25 26
605 24 25 26 27 28 29 30 28 29 27 28 29 30 31
606 31
607
608 April May June
609 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
610 1 2 1 2 3 4 5 6 7 1 2 3 4
611 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11
612 10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18
613 17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25
614 24 25 26 27 28 29 30 29 30 31 26 27 28 29 30
615
616 July August September
617 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
618 1 2 1 2 3 4 5 6 1 2 3
619 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10
620 10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17
621 17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24
622 24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30
623 31
624
625 October November December
626 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
627 1 1 2 3 4 5 1 2 3
628 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10
629 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17
630 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24
631 23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31
632 30 31
633
634
635 The following options are accepted:
636
637 .. program:: calendar
638
639
640 .. option:: --help, -h
641
642 Show the help message and exit.
643
644
645 .. option:: --locale LOCALE, -L LOCALE
646
647 The locale to use for month and weekday names.
648 Defaults to English.
649
650
651 .. option:: --encoding ENCODING, -e ENCODING
652
653 The encoding to use for output.
654 :option:`--encoding` is required if :option:`--locale` is set.
655
656
657 .. option:: --type {text,html}, -t {text,html}
658
659 Print the calendar to the terminal as text,
660 or as an HTML document.
661
662
663 .. option:: --first-weekday FIRST_WEEKDAY, -f FIRST_WEEKDAY
664
665 The weekday to start each week.
666 Must be a number between 0 (Monday) and 6 (Sunday).
667 Defaults to 0.
668
669 .. versionadded:: 3.13
670
671 .. option:: year
672
673 The year to print the calendar for.
674 Defaults to the current year.
675
676
677 .. option:: month
678
679 The month of the specified :option:`year` to print the calendar for.
680 Must be a number between 1 and 12,
681 and may only be used in text mode.
682 Defaults to printing a calendar for the full year.
683
684
685 *Text-mode options:*
686
687 .. option:: --width WIDTH, -w WIDTH
688
689 The width of the date column in terminal columns.
690 The date is printed centred in the column.
691 Any value lower than 2 is ignored.
692 Defaults to 2.
693
694
695 .. option:: --lines LINES, -l LINES
696
697 The number of lines for each week in terminal rows.
698 The date is printed top-aligned.
699 Any value lower than 1 is ignored.
700 Defaults to 1.
701
702
703 .. option:: --spacing SPACING, -s SPACING
704
705 The space between months in columns.
706 Any value lower than 2 is ignored.
707 Defaults to 6.
708
709
710 .. option:: --months MONTHS, -m MONTHS
711
712 The number of months printed per row.
713 Defaults to 3.
714
715
716 *HTML-mode options:*
717
718 .. option:: --css CSS, -c CSS
719
720 The path of a CSS stylesheet to use for the calendar.
721 This must either be relative to the generated HTML,
722 or an absolute HTTP or ``file:///`` URL.