# `calendar` --- 一般的なカレンダーに関係する機能群

ソースコード: Lib/calendar.py

このモジュールは Unix の cal プログラムのようなカレンダー出力を行い、それに加えてカレンダーに関する有益な関数群を提供します。標準ではこれらのカレンダーは（ヨーロッパの慣例に従って）月曜日を週の始まりとし、日曜日を最後の日としています。 `setfirstweekday()` を用いることで、日曜日(6)や他の曜日を週の始まりに設定することができます。日付を表す引数は整数値で与えます。関連する機能として、 `datetime` と `time` モジュールも参照してください。

このモジュールに定義された関数やクラスは理想化されたカレンダー、つまり現在のグレゴリオ暦を過去と未来両方に無限に拡張したものを使っています。これはすべての計算の基礎のカレンダーとなっている、 Dershowitz と Reingold の本 "Calendrical Calculations" 中の "proleptic Gregorian" のカレンダーの定義に合致します。ゼロと負の年は ISO 8601 の基準に定められている通りに扱われます。0 年は 1 BC、-1 年は 2 BC、のように続きます。

class calendar.Calendar(firstweekday=0)

  `Calendar` オブジェクトを作ります。 firstweekday は整数で週の始まりの曜日を指定するものです。`MONDAY` が `0` (デフォルト)、`SUNDAY` なら `6` です。

  `Calendar` オブジェクトは整形されるカレンダーのデータを準備するために使えるいくつかのメソッドを提供しています。しかし整形機能そのものは提供していません。それはサブクラスの仕事なのです。

  `Calendar` instances have the following methods and attributes:

  firstweekday

    The first weekday as an integer (0--6).

    This property can also be set and read using `setfirstweekday()` and `getfirstweekday()` respectively.

  getfirstweekday()

    Return an `int` for the current first weekday (0--6).

    Identical to reading the `firstweekday` property.

  setfirstweekday(firstweekday)

    Set the first weekday to firstweekday, passed as an `int` (0--6).

    Identical to setting the `firstweekday` property.

  iterweekdays()

    Return an iterator for the weekday numbers that will be used for one week. The first value from the iterator will be the same as the value of the `firstweekday` property.

  itermonthdates(year, month)

    year 年 month (1--12) 月に対するイテレータを返します。 このイテレータはその月の全ての日、およびその月が始まる前の日とその月が終わった後の日のうち、週の欠けを埋めるために必要な日を (`datetime.date` オブジェクトとして) 返します。

  itermonthdays(year, month)

    Return an iterator for the month month in the year year similar to `itermonthdates()`, but not restricted by the `datetime.date` range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is `0`.

  itermonthdays2(year, month)

    Return an iterator for the month month in the year year similar to `itermonthdates()`, but not restricted by the `datetime.date` range. Days returned will be tuples consisting of a day of the month number and a weekday number.

  itermonthdays3(year, month)

    Return an iterator for the month month in the year year similar to `itermonthdates()`, but not restricted by the `datetime.date` range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.

    Added in version 3.7.

  itermonthdays4(year, month)

    Return an iterator for the month month in the year year similar to `itermonthdates()`, but not restricted by the `datetime.date` range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.

    Added in version 3.7.

  monthdatescalendar(year, month)

    year 年 month 月の週のリストを返します。週は全て七つの `datetime.date` オブジェクトからなるリストです。

  monthdays2calendar(year, month)

    year 年 month 月の週のリストを返します。週は全て七つの日付の数字と曜日を表す数字のタプルからなるリストです。

  monthdayscalendar(year, month)

    year 年 month 月の週のリストを返します。週は全て七つの日付の数字からなるリストです。

  yeardatescalendar(year, width=3)

    指定された年のデータを整形に向く形で返します。返される値は月の並びのリストです。月の並びは最大で width ヶ月(デフォルトは3ヶ月)分です。各月は4ないし6週からなり、各週は1ないし7日からなります。各日は `datetime.date` オブジェクトです。

  yeardays2calendar(year, width=3)

    指定された年のデータを整形に向く形で返します (`yeardatescalendar()` と同様です)。週のリストの中が日付の数字と曜日の数字のタプルになります。月の範囲外の部分の日付はゼロです。

  yeardayscalendar(year, width=3)

    指定された年のデータを整形に向く形で返します (`yeardatescalendar()` と同様です)。週のリストの中が日付の数字になります。月の範囲外の日付はゼロです。

class calendar.TextCalendar(firstweekday=0)

  このクラスはプレインテキストのカレンダーを生成するのに使えます。

  `TextCalendar` インスタンスには以下のメソッドがあります:

  prweek(theweek, width)

    Print a week's calendar as returned by `formatweek()` and without a final newline.

  formatday(theday, weekday, width)

    Return a string representing a single day formatted with the given width. If theday is `0`, return a string of spaces of the specified width, representing an empty day. The weekday parameter is unused.

  formatweek(theweek, w=0)

    Return a single week in a string with no newline. If w is provided, it specifies the width of the date columns, which are centered. Depends on the first weekday as specified in the constructor or set by the `setfirstweekday()` method.

  formatweekday(weekday, width)

    Return a string representing the name of a single weekday formatted to the specified width. The weekday parameter is an integer representing the day of the week, where `0` is Monday and `6` is Sunday.

  formatweekheader(width)

    Return a string containing the header row of weekday names, formatted with the given width for each column. The names depend on the locale settings and are padded to the specified width.

  formatmonth(theyear, themonth, w=0, l=0)

    ひと月分のカレンダーを複数行の文字列で返します。 w により日の列幅を変えることができ、それらは中央揃えされます。 l により各週の表示される行数を変えることができます。 `setfirstweekday()` メソッドでセットされた週の最初の曜日に依存します。

  formatmonthname(theyear, themonth, width=0, withyear=True)

    Return a string representing the month's name centered within the specified width. If withyear is `True`, include the year in the output. The theyear and themonth parameters specify the year and month for the name to be formatted respectively.

  prmonth(theyear, themonth, w=0, l=0)

    `formatmonth()` で返されるひと月分のカレンダーを出力します。

  formatyear(theyear, w=2, l=1, c=6, m=3)

    m 列からなる一年間のカレンダーを複数行の文字列で返します。任意の引数 w, l, c はそれぞれ、日付列の表示幅、各週の行数及び月と月の間のスペースの数を変更するためのものです。 `setfirstweekday()` メソッドでセットされた週の最初の曜日に依存します。カレンダーを出力できる最初の年はプラットフォームに依存します。

  pryear(theyear, w=2, l=1, c=6, m=3)

    `formatyear()` で返される一年間のカレンダーを出力します。

class calendar.HTMLCalendar(firstweekday=0)

  このクラスは HTML のカレンダーを生成するのに使えます。

  `HTMLCalendar` インスタンスには以下のメソッドがあります:

  formatmonth(theyear, themonth, withyear=True)

    ひと月分のカレンダーを HTML のテーブルとして返します。withyear が真であればヘッダには年も含まれます。そうでなければ月の名前だけが使われます。

  formatyear(theyear, width=3)

    一年分のカレンダーを HTML のテーブルとして返します。width の値 (デフォルトでは 3 です) は何ヶ月分を一行に収めるかを指定します。

  formatyearpage(theyear, width=3, css='calendar.css', encoding=None)

    Return a year's calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. `None` can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to `'utf-8'`).

  formatmonthname(theyear, themonth, withyear=True)

    Return a month name as an HTML table row. If withyear is true the year will be included in the row, otherwise just the month name will be used.

  `HTMLCalendar` has the following attributes you can override to customize the CSS classes used by the calendar:

  cssclasses

    A list of CSS classes used for each weekday. The default class list is:

        cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

    more styles can be added for each day:

        cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]

    Note that the length of this list must be seven items.

  cssclass_noday

    The CSS class for a weekday occurring in the previous or coming month.

    Added in version 3.7.

  cssclasses_weekday_head

    A list of CSS classes used for weekday names in the header row. The default is the same as `cssclasses`.

    Added in version 3.7.

  cssclass_month_head

    The month's head CSS class (used by `formatmonthname()`). The default value is `"month"`.

    Added in version 3.7.

  cssclass_month

    The CSS class for the whole month's table (used by `formatmonth()`). The default value is `"month"`.

    Added in version 3.7.

  cssclass_year

    The CSS class for the whole year's table of tables (used by `formatyear()`). The default value is `"year"`.

    Added in version 3.7.

  cssclass_year_head

    The CSS class for the table head for the whole year (used by `formatyear()`). The default value is `"year"`.

    Added in version 3.7.

  Note that although the naming for the above described class attributes is singular (e.g. `cssclass_month` `cssclass_noday`), one can replace the single CSS class with a space separated list of CSS classes, for example:

      "text-bold text-red"

  Here is an example how `HTMLCalendar` can be customized:

      class CustomHTMLCal(calendar.HTMLCalendar):
          cssclasses = [style + " text-nowrap" for style in
                        calendar.HTMLCalendar.cssclasses]
          cssclass_month_head = "text-center month-head"
          cssclass_month = "text-center month"
          cssclass_year = "text-italic lead"

class calendar.LocaleTextCalendar(firstweekday=0, locale=None)

  This subclass of `TextCalendar` can be passed a locale name in the constructor and will return month and weekday names in the specified locale.

class calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)

  This subclass of `HTMLCalendar` can be passed a locale name in the constructor and will return month and weekday names in the specified locale.

注釈

The constructor, `formatweekday()` and `formatmonthname()` methods of these two classes temporarily change the `LC_TIME` locale to the given locale. Because the current locale is a process-wide setting, they are not thread-safe.

単純なテキストのカレンダーに関して、このモジュールには以下のような関数が提供されています。

calendar.setfirstweekday(weekday)

  週の最初の曜日(`0` は月曜日, `6` は日曜日)を設定します。定数 `MONDAY`, `TUESDAY`, `WEDNESDAY`, `THURSDAY`, `FRIDAY`, `SATURDAY` 及び `SUNDAY` は便宜上提供されています。例えば、日曜日を週の開始日に設定するときは:

      import calendar
      calendar.setfirstweekday(calendar.SUNDAY)

calendar.firstweekday()

  現在設定されている週の最初の曜日を返します。

calendar.isleap(year)

  year が閏年なら `True` を、そうでなければ `False` を返します。

calendar.leapdays(y1, y2)

  範囲(y1 ... y2)指定された期間の閏年の回数を返します。ここで y1 や y2 は年を表します。

  この関数は、世紀の境目をまたぐ範囲でも正しく動作します。

calendar.weekday(year, month, day)

  year (`1970`--...), month (`1`--`12`), day (`1`--`31`) で与えられた日の曜日(`0` は月曜日)を返します。

calendar.weekheader(n)

  短縮された曜日名を含むヘッダを返します。n は各曜日を何文字で表すかを指定します。

calendar.monthrange(year, month)

  Returns weekday of first day of the month and number of days in month, for the specified year and month.

calendar.monthcalendar(year, month)

  月のカレンダーを行列で返します。各行が週を表し、月の範囲外の日は0になります。それぞれの週は `setfirstweekday()` で設定をしていない限り月曜日から始まります。

calendar.prmonth(theyear, themonth, w=0, l=0)

  `month()` 関数によって返される月のカレンダーを出力します。

calendar.month(theyear, themonth, w=0, l=0)

  Returns a month's calendar in a multi-line string using the `formatmonth()` of the `TextCalendar` class.

calendar.prcal(year, w=0, l=0, c=6, m=3)

  `calendar()` 関数で返される一年間のカレンダーを出力します。

calendar.calendar(year, w=2, l=1, c=6, m=3)

  Returns a 3-column calendar for an entire year as a multi-line string using the `formatyear()` of the `TextCalendar` class.

calendar.timegm(tuple)

  An unrelated but handy function that takes a time tuple such as returned by the `gmtime()` function in the `time` module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, `time.gmtime()` and `timegm()` are each other's inverse.

The `calendar` module exports the following data attributes:

calendar.day_name

  A sequence that represents the days of the week in the current locale, where Monday is day number 0.

      >>> import calendar
      >>> list(calendar.day_name)
      ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

calendar.day_abbr

  A sequence that represents the abbreviated days of the week in the current locale, where Mon is day number 0.

      >>> import calendar
      >>> list(calendar.day_abbr)
      ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

calendar.MONDAY
calendar.TUESDAY
calendar.WEDNESDAY
calendar.THURSDAY
calendar.FRIDAY
calendar.SATURDAY
calendar.SUNDAY

  Aliases for the days of the week, where `MONDAY` is `0` and `SUNDAY` is `6`.

  Added in version 3.12.

class calendar.Day

  Enumeration defining days of the week as integer constants. The members of this enumeration are exported to the module scope as `MONDAY` through `SUNDAY`.

  Added in version 3.12.

calendar.month_name

  A sequence that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and `month_name[0]` is the empty string.

      >>> import calendar
      >>> list(calendar.month_name)
      ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

  注意

  In locales with alternative month names forms, the `month_name` sequence may not be suitable when a month name stands by itself and not as part of a date. For instance, in Greek and in many Slavic and Baltic languages, `month_name` will produce the month in genitive case. Use `standalone_month_name` for a form suitable for standalone use.

calendar.month_abbr

  A sequence that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and `month_abbr[0]` is the empty string.

      >>> import calendar
      >>> list(calendar.month_abbr)
      ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

  注意

  In locales with alternative month names forms, the `month_abbr` sequence may not be suitable when a month name stands by itself and not as part of a date. Use `standalone_month_abbr` for a form suitable for standalone use.

calendar.standalone_month_name

  A sequence that represents the months of the year in the current locale in the standalone form if the locale provides one. Else it is equivalent to `month_name`.

  Added in version 3.15.

calendar.standalone_month_abbr

  A sequence that represents the abbreviated months of the year in the current locale in the standalone form if the locale provides one. Else it is equivalent to `month_abbr`.

  Added in version 3.15.

calendar.JANUARY
calendar.FEBRUARY
calendar.MARCH
calendar.APRIL
calendar.MAY
calendar.JUNE
calendar.JULY
calendar.AUGUST
calendar.SEPTEMBER
calendar.OCTOBER
calendar.NOVEMBER
calendar.DECEMBER

  Aliases for the months of the year, where `JANUARY` is `1` and `DECEMBER` is `12`.

  Added in version 3.12.

class calendar.Month

  Enumeration defining months of the year as integer constants. The members of this enumeration are exported to the module scope as `JANUARY` through `DECEMBER`.

  Added in version 3.12.

The `calendar` module defines the following exceptions:

exception calendar.IllegalMonthError(month)

  A subclass of `ValueError` and `IndexError`, raised when the given month number is outside of the range 1-12 (inclusive).

  バージョン 3.12 で変更: `IllegalMonthError` is now also a subclass of `ValueError`. New code should avoid catching `IndexError`.

  month

    The invalid month number.

exception calendar.IllegalWeekdayError(weekday)

  A subclass of `ValueError`, raised when the given weekday number is outside of the range 0-6 (inclusive).

  weekday

    The invalid weekday number.

参考

`datetime` モジュール

  `time` モジュールと似た機能を持った日付と時間用のオブジェクト指向インターフェース。

`time` モジュール

  時間に関連した低水準の関数群。

## コマンドラインでの使用

Added in version 2.5.

The `calendar` module can be executed as a script from the command line to interactively print a calendar.

    python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]
                       [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]
                       [-f FIRST_WEEKDAY] [year] [month]

For example, to print a calendar for the year 2000:

    $ python -m calendar 2000
                                      2000

          January                   February                   March
    Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                    1  2          1  2  3  4  5  6             1  2  3  4  5
     3  4  5  6  7  8  9       7  8  9 10 11 12 13       6  7  8  9 10 11 12
    10 11 12 13 14 15 16      14 15 16 17 18 19 20      13 14 15 16 17 18 19
    17 18 19 20 21 22 23      21 22 23 24 25 26 27      20 21 22 23 24 25 26
    24 25 26 27 28 29 30      28 29                     27 28 29 30 31
    31

           April                      May                       June
    Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                    1  2       1  2  3  4  5  6  7                1  2  3  4
     3  4  5  6  7  8  9       8  9 10 11 12 13 14       5  6  7  8  9 10 11
    10 11 12 13 14 15 16      15 16 17 18 19 20 21      12 13 14 15 16 17 18
    17 18 19 20 21 22 23      22 23 24 25 26 27 28      19 20 21 22 23 24 25
    24 25 26 27 28 29 30      29 30 31                  26 27 28 29 30

            July                     August                  September
    Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                    1  2          1  2  3  4  5  6                   1  2  3
     3  4  5  6  7  8  9       7  8  9 10 11 12 13       4  5  6  7  8  9 10
    10 11 12 13 14 15 16      14 15 16 17 18 19 20      11 12 13 14 15 16 17
    17 18 19 20 21 22 23      21 22 23 24 25 26 27      18 19 20 21 22 23 24
    24 25 26 27 28 29 30      28 29 30 31               25 26 27 28 29 30
    31

          October                   November                  December
    Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                       1             1  2  3  4  5                   1  2  3
     2  3  4  5  6  7  8       6  7  8  9 10 11 12       4  5  6  7  8  9 10
     9 10 11 12 13 14 15      13 14 15 16 17 18 19      11 12 13 14 15 16 17
    16 17 18 19 20 21 22      20 21 22 23 24 25 26      18 19 20 21 22 23 24
    23 24 25 26 27 28 29      27 28 29 30               25 26 27 28 29 30 31
    30 31

以下のオプションが使用できます:

--help, -h

  ヘルプメッセージを表示して終了します。

--locale LOCALE, -L LOCALE

  The locale to use for month and weekday names. Defaults to English.

--encoding ENCODING, -e ENCODING

  The encoding to use for output. `--encoding` is required if `--locale` is set.

--type {text,html}, -t {text,html}

  Print the calendar to the terminal as text, or as an HTML document.

--first-weekday FIRST_WEEKDAY, -f FIRST_WEEKDAY

  The weekday to start each week. Must be a number between 0 (Monday) and 6 (Sunday). Defaults to 0.

  Added in version 3.13.

year

  The year to print the calendar for. Defaults to the current year.

month

  The month of the specified `year` to print the calendar for. Must be a number between 1 and 12. Defaults to printing a calendar for the full year.

Text-mode options:

--width WIDTH, -w WIDTH

  The width of the date column in terminal columns. The date is printed centred in the column. Any value lower than 2 is ignored. Defaults to 2.

--lines LINES, -l LINES

  The number of lines for each week in terminal rows. The date is printed top-aligned. Any value lower than 1 is ignored. Defaults to 1.

--spacing SPACING, -s SPACING

  The space between months in columns. Any value lower than 2 is ignored. Defaults to 6.

--months MONTHS, -m MONTHS

  The number of months printed per row. Defaults to 3.

バージョン 3.14 で変更: By default, today's date is highlighted in color and can be controlled using environment variables.

バージョン 3.15 で変更: By default, the month is now also highlighted in color, and the days of the week are also in color. This behavior can be controlled using environment variables.

HTML-mode options:

--css CSS, -c CSS

  The path of a CSS stylesheet to use for the calendar. This must either be relative to the generated HTML, or an absolute HTTP or `file:///` URL.