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
177 .. method:: formatweekday(weekday, width)
178
179 Return a string representing the name of a single weekday formatted to
180 the specified *width*. The *weekday* parameter is an integer representing
181 the day of the week, where ``0`` is Monday and ``6`` is Sunday.
182
183
184 .. method:: formatweekheader(width)
185
186 Return a string containing the header row of weekday names, formatted
187 with the given *width* for each column. The names depend on the locale
188 settings and are padded to the specified width.
189
190
191 .. method:: formatmonth(theyear, themonth, w=0, l=0)
192
193 Return a month's calendar in a multi-line string. If *w* is provided, it
194 specifies the width of the date columns, which are centered. If *l* is
195 given, it specifies the number of lines that each week will use. Depends
196 on the first weekday as specified in the constructor or set by the
197 :meth:`setfirstweekday` method.
198
199
200 .. method:: formatmonthname(theyear, themonth, width=0, withyear=True)
201
202 Return a string representing the month's name centered within the
203 specified *width*. If *withyear* is ``True``, include the year in the
204 output. The *theyear* and *themonth* parameters specify the year
205 and month for the name to be formatted respectively.
206
207
208 .. method:: prmonth(theyear, themonth, w=0, l=0)
209
210 Print a month's calendar as returned by :meth:`formatmonth`.
211
212
213 .. method:: formatyear(theyear, w=2, l=1, c=6, m=3)
214
215 Return a *m*-column calendar for an entire year as a multi-line string.
216 Optional parameters *w*, *l*, and *c* are for date column width, lines per
217 week, and number of spaces between month columns, respectively. Depends on
218 the first weekday as specified in the constructor or set by the
219 :meth:`setfirstweekday` method. The earliest year for which a calendar
220 can be generated is platform-dependent.
221
222
223 .. method:: pryear(theyear, w=2, l=1, c=6, m=3)
224
225 Print the calendar for an entire year as returned by :meth:`formatyear`.
226
227
228 .. class:: HTMLCalendar(firstweekday=0)
229
230 This class can be used to generate HTML calendars.
231
232
233 :class:`!HTMLCalendar` instances have the following methods:
234
235 .. method:: formatmonth(theyear, themonth, withyear=True)
236
237 Return a month's calendar as an HTML table. If *withyear* is true the year
238 will be included in the header, otherwise just the month name will be
239 used.
240
241
242 .. method:: formatyear(theyear, width=3)
243
244 Return a year's calendar as an HTML table. *width* (defaulting to 3)
245 specifies the number of months per row.
246
247
248 .. method:: formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
249
250 Return a year's calendar as a complete HTML page. *width* (defaulting to
251 3) specifies the number of months per row. *css* is the name for the
252 cascading style sheet to be used. :const:`None` can be passed if no style
253 sheet should be used. *encoding* specifies the encoding to be used for the
254 output (defaulting to the system default encoding).
255
256
257 .. method:: formatmonthname(theyear, themonth, withyear=True)
258
259 Return a month name as an HTML table row. If *withyear* is true the year
260 will be included in the row, otherwise just the month name will be
261 used.
262
263
264 :class:`!HTMLCalendar` has the following attributes you can override to
265 customize the CSS classes used by the calendar:
266
267 .. attribute:: cssclasses
268
269 A list of CSS classes used for each weekday. The default class list is::
270
271 cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
272
273 more styles can be added for each day::
274
275 cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
276
277 Note that the length of this list must be seven items.
278
279
280 .. attribute:: cssclass_noday
281
282 The CSS class for a weekday occurring in the previous or coming month.
283
284 .. versionadded:: 3.7
285
286
287 .. attribute:: cssclasses_weekday_head
288
289 A list of CSS classes used for weekday names in the header row.
290 The default is the same as :attr:`cssclasses`.
291
292 .. versionadded:: 3.7
293
294
295 .. attribute:: cssclass_month_head
296
297 The month's head CSS class (used by :meth:`formatmonthname`).
298 The default value is ``"month"``.
299
300 .. versionadded:: 3.7
301
302
303 .. attribute:: cssclass_month
304
305 The CSS class for the whole month's table (used by :meth:`formatmonth`).
306 The default value is ``"month"``.
307
308 .. versionadded:: 3.7
309
310
311 .. attribute:: cssclass_year
312
313 The CSS class for the whole year's table of tables (used by
314 :meth:`formatyear`). The default value is ``"year"``.
315
316 .. versionadded:: 3.7
317
318
319 .. attribute:: cssclass_year_head
320
321 The CSS class for the table head for the whole year (used by
322 :meth:`formatyear`). The default value is ``"year"``.
323
324 .. versionadded:: 3.7
325
326
327 Note that although the naming for the above described class attributes is
328 singular (e.g. ``cssclass_month`` ``cssclass_noday``), one can replace the
329 single CSS class with a space separated list of CSS classes, for example::
330
331 "text-bold text-red"
332
333 Here is an example how :class:`!HTMLCalendar` can be customized::
334
335 class CustomHTMLCal(calendar.HTMLCalendar):
336 cssclasses = [style + " text-nowrap" for style in
337 calendar.HTMLCalendar.cssclasses]
338 cssclass_month_head = "text-center month-head"
339 cssclass_month = "text-center month"
340 cssclass_year = "text-italic lead"
341
342
343 .. class:: LocaleTextCalendar(firstweekday=0, locale=None)
344
345 This subclass of :class:`TextCalendar` can be passed a locale name in the
346 constructor and will return month and weekday names in the specified locale.
347
348
349 .. class:: LocaleHTMLCalendar(firstweekday=0, locale=None)
350
351 This subclass of :class:`HTMLCalendar` can be passed a locale name in the
352 constructor and will return month and weekday names in the specified
353 locale.
354
355 .. note::
356
357 The constructor, :meth:`!formatweekday` and :meth:`!formatmonthname` methods
358 of these two classes temporarily change the ``LC_TIME`` locale to the given
359 *locale*. Because the current locale is a process-wide setting, they are
360 not thread-safe.
361
362
363 For simple text calendars this module provides the following functions.
364
365 .. function:: setfirstweekday(weekday)
366
367 Sets the weekday (``0`` is Monday, ``6`` is Sunday) to start each week. The
368 values :const:`MONDAY`, :const:`TUESDAY`, :const:`WEDNESDAY`, :const:`THURSDAY`,
369 :const:`FRIDAY`, :const:`SATURDAY`, and :const:`SUNDAY` are provided for
370 convenience. For example, to set the first weekday to Sunday::
371
372 import calendar
373 calendar.setfirstweekday(calendar.SUNDAY)
374
375
376 .. function:: firstweekday()
377
378 Returns the current setting for the weekday to start each week.
379
380
381 .. function:: isleap(year)
382
383 Returns :const:`True` if *year* is a leap year, otherwise :const:`False`.
384
385
386 .. function:: leapdays(y1, y2)
387
388 Returns the number of leap years in the range from *y1* to *y2* (exclusive),
389 where *y1* and *y2* are years.
390
391 This function works for ranges spanning a century change.
392
393
394 .. function:: weekday(year, month, day)
395
396 Returns the day of the week (``0`` is Monday) for *year* (``1970``--...),
397 *month* (``1``--``12``), *day* (``1``--``31``).
398
399
400 .. function:: weekheader(n)
401
402 Return a header containing abbreviated weekday names. *n* specifies the width in
403 characters for one weekday.
404
405
406 .. function:: monthrange(year, month)
407
408 Returns weekday of first day of the month and number of days in month, for the
409 specified *year* and *month*.
410
411
412 .. function:: monthcalendar(year, month)
413
414 Returns a matrix representing a month's calendar. Each row represents a week;
415 days outside of the month are represented by zeros. Each week begins with Monday
416 unless set by :func:`setfirstweekday`.
417
418
419 .. function:: prmonth(theyear, themonth, w=0, l=0)
420
421 Prints a month's calendar as returned by :func:`month`.
422
423
424 .. function:: month(theyear, themonth, w=0, l=0)
425
426 Returns a month's calendar in a multi-line string using the :meth:`~TextCalendar.formatmonth`
427 of the :class:`TextCalendar` class.
428
429
430 .. function:: prcal(year, w=0, l=0, c=6, m=3)
431
432 Prints the calendar for an entire year as returned by :func:`calendar`.
433
434
435 .. function:: calendar(year, w=2, l=1, c=6, m=3)
436
437 Returns a 3-column calendar for an entire year as a multi-line string using
438 the :meth:`~TextCalendar.formatyear` of the :class:`TextCalendar` class.
439
440
441 .. function:: timegm(tuple)
442
443 An unrelated but handy function that takes a time tuple such as returned by
444 the :func:`~time.gmtime` function in the :mod:`time` module, and returns the
445 corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX
446 encoding. In fact, :func:`time.gmtime` and :func:`timegm` are each other's
447 inverse.
448
449
450 The :mod:`!calendar` module exports the following data attributes:
451
452 .. data:: day_name
453
454 A sequence that represents the days of the week in the current locale,
455 where Monday is day number 0.
456
457 >>> import calendar
458 >>> list(calendar.day_name)
459 ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
460
461
462 .. data:: day_abbr
463
464 A sequence that represents the abbreviated days of the week in the current locale,
465 where Mon is day number 0.
466
467 >>> import calendar
468 >>> list(calendar.day_abbr)
469 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
470
471 .. data:: MONDAY
472 TUESDAY
473 WEDNESDAY
474 THURSDAY
475 FRIDAY
476 SATURDAY
477 SUNDAY
478
479 Aliases for the days of the week,
480 where ``MONDAY`` is ``0`` and ``SUNDAY`` is ``6``.
481
482 .. versionadded:: 3.12
483
484
485 .. class:: Day
486
487 Enumeration defining days of the week as integer constants.
488 The members of this enumeration are exported to the module scope as
489 :data:`MONDAY` through :data:`SUNDAY`.
490
491 .. versionadded:: 3.12
492
493
494 .. data:: month_name
495
496 A sequence that represents the months of the year in the current locale. This
497 follows normal convention of January being month number 1, so it has a length of
498 13 and ``month_name[0]`` is the empty string.
499
500 >>> import calendar
501 >>> list(calendar.month_name)
502 ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
503
504
505 .. data:: month_abbr
506
507 A sequence that represents the abbreviated months of the year in the current
508 locale. This follows normal convention of January being month number 1, so it
509 has a length of 13 and ``month_abbr[0]`` is the empty string.
510
511 >>> import calendar
512 >>> list(calendar.month_abbr)
513 ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
514
515 .. data:: JANUARY
516 FEBRUARY
517 MARCH
518 APRIL
519 MAY
520 JUNE
521 JULY
522 AUGUST
523 SEPTEMBER
524 OCTOBER
525 NOVEMBER
526 DECEMBER
527
528 Aliases for the months of the year,
529 where ``JANUARY`` is ``1`` and ``DECEMBER`` is ``12``.
530
531 .. versionadded:: 3.12
532
533
534 .. class:: Month
535
536 Enumeration defining months of the year as integer constants.
537 The members of this enumeration are exported to the module scope as
538 :data:`JANUARY` through :data:`DECEMBER`.
539
540 .. versionadded:: 3.12
541
542
543 The :mod:`!calendar` module defines the following exceptions:
544
545 .. exception:: IllegalMonthError(month)
546
547 A subclass of :exc:`ValueError` and :exc:`IndexError`,
548 raised when the given month number is outside of the range 1-12 (inclusive).
549
550 .. versionchanged:: 3.12
551 :exc:`IllegalMonthError` is now also a subclass of
552 :exc:`ValueError`. New code should avoid catching
553 :exc:`IndexError`.
554
555 .. attribute:: month
556
557 The invalid month number.
558
559
560 .. exception:: IllegalWeekdayError(weekday)
561
562 A subclass of :exc:`ValueError`,
563 raised when the given weekday number is outside of the range 0-6 (inclusive).
564
565 .. attribute:: weekday
566
567 The invalid weekday number.
568
569
570 .. seealso::
571
572 Module :mod:`datetime`
573 Object-oriented interface to dates and times with similar functionality to the
574 :mod:`time` module.
575
576 Module :mod:`time`
577 Low-level time related functions.
578
579
580 .. _calendar-cli:
581
582 Command-line usage
583 ------------------
584
585 .. versionadded:: 2.5
586
587 The :mod:`!calendar` module can be executed as a script from the command line
588 to interactively print a calendar.
589
590 .. code-block:: shell
591
592 python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]
593 [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]
594 [-f FIRST_WEEKDAY] [year] [month]
595
596
597 For example, to print a calendar for the year 2000:
598
599 .. code-block:: console
600
601 $ python -m calendar 2000
602 2000
603
604 January February March
605 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
606 1 2 1 2 3 4 5 6 1 2 3 4 5
607 3 4 5 6 7 8 9 7 8 9 10 11 12 13 6 7 8 9 10 11 12
608 10 11 12 13 14 15 16 14 15 16 17 18 19 20 13 14 15 16 17 18 19
609 17 18 19 20 21 22 23 21 22 23 24 25 26 27 20 21 22 23 24 25 26
610 24 25 26 27 28 29 30 28 29 27 28 29 30 31
611 31
612
613 April May June
614 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
615 1 2 1 2 3 4 5 6 7 1 2 3 4
616 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11
617 10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18
618 17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25
619 24 25 26 27 28 29 30 29 30 31 26 27 28 29 30
620
621 July August September
622 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
623 1 2 1 2 3 4 5 6 1 2 3
624 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10
625 10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17
626 17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24
627 24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30
628 31
629
630 October November December
631 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
632 1 1 2 3 4 5 1 2 3
633 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10
634 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17
635 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24
636 23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31
637 30 31
638
639
640 The following options are accepted:
641
642 .. program:: calendar
643
644
645 .. option:: --help, -h
646
647 Show the help message and exit.
648
649
650 .. option:: --locale LOCALE, -L LOCALE
651
652 The locale to use for month and weekday names.
653 Defaults to English.
654
655
656 .. option:: --encoding ENCODING, -e ENCODING
657
658 The encoding to use for output.
659 :option:`--encoding` is required if :option:`--locale` is set.
660
661
662 .. option:: --type {text,html}, -t {text,html}
663
664 Print the calendar to the terminal as text,
665 or as an HTML document.
666
667
668 .. option:: --first-weekday FIRST_WEEKDAY, -f FIRST_WEEKDAY
669
670 The weekday to start each week.
671 Must be a number between 0 (Monday) and 6 (Sunday).
672 Defaults to 0.
673
674 .. versionadded:: 3.13
675
676 .. option:: year
677
678 The year to print the calendar for.
679 Defaults to the current year.
680
681
682 .. option:: month
683
684 The month of the specified :option:`year` to print the calendar for.
685 Must be a number between 1 and 12,
686 and may only be used in text mode.
687 Defaults to printing a calendar for the full year.
688
689
690 *Text-mode options:*
691
692 .. option:: --width WIDTH, -w WIDTH
693
694 The width of the date column in terminal columns.
695 The date is printed centred in the column.
696 Any value lower than 2 is ignored.
697 Defaults to 2.
698
699
700 .. option:: --lines LINES, -l LINES
701
702 The number of lines for each week in terminal rows.
703 The date is printed top-aligned.
704 Any value lower than 1 is ignored.
705 Defaults to 1.
706
707
708 .. option:: --spacing SPACING, -s SPACING
709
710 The space between months in columns.
711 Any value lower than 2 is ignored.
712 Defaults to 6.
713
714
715 .. option:: --months MONTHS, -m MONTHS
716
717 The number of months printed per row.
718 Defaults to 3.
719
720 .. versionchanged:: 3.14
721 By default, today's date is highlighted in color and can be
722 :ref:`controlled using environment variables <using-on-controlling-color>`.
723
724 *HTML-mode options:*
725
726 .. option:: --css CSS, -c CSS
727
728 The path of a CSS stylesheet to use for the calendar.
729 This must either be relative to the generated HTML,
730 or an absolute HTTP or ``file:///`` URL.