"time" — 時刻データへのアクセスと変換
*************************************

このモジュールでは、時刻に関するさまざまな関数を提供します。関連した機
能について、"datetime", "calendar" モジュールも参照してください。

このモジュールは常に利用可能ですが、すべての関数がすべてのプラットフォ
ームで利用可能なわけではありません。このモジュールで定義されているほと
んどの関数は、プラットフォーム上の同名の C ライブラリ関数を呼び出しま
す。これらの関数に対する意味付けはプラットフォーム間で異なるため、プラ
ットフォーム提供のドキュメントを読んでおくと便利でしょう。

まずいくつかの用語の説明と慣習について整理します。

* The *epoch* is the point where the time starts.  On January 1st of
  that year, at 0 hours, the 「time since the epoch」 is zero.  For
  Unix, the epoch is 1970.  To find out what the epoch is, look at
  "gmtime(0)".

* The functions in this module do not handle dates and times before
  the epoch or far in the future.  The cut-off point in the future is
  determined by the C library; for Unix, it is typically in 2038.

* **Year 2000 (Y2K) issues**:  Python depends on the platform’s C
  library, which generally doesn’t have year 2000 issues, since all
  dates and times are represented internally as seconds since the
  epoch.  Functions accepting a "struct_time" (see below) generally
  require a 4-digit year.  For backward compatibility, 2-digit years
  are supported if the module variable "accept2dyear" is a non-zero
  integer; this variable is initialized to "1" unless the environment
  variable "PYTHONY2K" is set to a non-empty string, in which case it
  is initialized to "0".  Thus, you can set "PYTHONY2K" to a non-empty
  string in the environment to require 4-digit years for all year
  input.  When 2-digit years are accepted, they are converted
  according to the POSIX or X/Open standard: values 69-99 are mapped
  to 1969-1999, and values 0–68 are mapped to 2000–2068. Values
  100–1899 are always illegal.

* UTC は協定世界時 (Coordinated Universal Time) のことです (以前はグ
  リ ニッジ標準時または GMT として知られていました)。UTC の頭文字の並
  びは 誤りではなく、英仏の妥協によるものです。

* DST は夏時間 (Daylight Saving Time) のことで、一年のうちの一定期間
  に 1 時間タイムゾーンを修正することです。DST のルールは不可思議で (
  地域 ごとに法律で定められています)、年ごとに変わることもあります。C
  ライ ブラリはローカルルールを記したテーブルを持っており (柔軟に対応
  するた め、たいていはシステムファイルから読み込まれます)、この点に関
  しては 唯一の真実の知識の源です。

* 多くの現時刻を返す関数 (real-time functions) の精度は、値や引数を
  表 現するために使う単位から想像されるよりも低いかも知れません。例え
  ば、 ほとんどの Unix システムにおいて、クロックの 1 ティックの精度は
  50 から 100 分の 1 秒に過ぎません。

* 一方、"time()" および "sleep()" は Unix の同等の関数よりましな精度
  を 持っています。時刻は浮動小数点数で表され、"time()" は可能なかぎり
  最 も正確な時刻を (Unix の "gettimeofday()" があればそれを使って) 返
  し ます。また "sleep()" にはゼロでない端数を与えることができます
  (Unix の "select()" があれば、それを使って実装しています)。

* The time value as returned by "gmtime()", "localtime()", and
  "strptime()", and accepted by "asctime()", "mktime()" and
  "strftime()", may be considered as a sequence of 9 integers.  The
  return values of "gmtime()", "localtime()", and "strptime()" also
  offer attribute names for individual fields.

  これらのオブジェクトについての解説は "struct_time" を参照してくださ
  い。

  バージョン 2.2 で変更: The time value sequence was changed from a
  tuple to a "struct_time", with the addition of attribute names for
  the fields.

* 時間の表現を変換するには、以下の関数を利用してください:

  +---------------------------+---------------------------+---------------------------+
  | 対象                      | 変換先                    | 関数                      |
  +===========================+===========================+===========================+
  | エポックからの秒数        | UTC の "struct_time"      | "gmtime()"                |
  +---------------------------+---------------------------+---------------------------+
  | エポックからの秒数        | ローカル時間の            | "localtime()"             |
  |                           | "struct_time"             |                           |
  +---------------------------+---------------------------+---------------------------+
  | UTC の "struct_time"      | エポックからの秒数        | "calendar.timegm()"       |
  +---------------------------+---------------------------+---------------------------+
  | ローカル時間の            | エポックからの秒数        | "mktime()"                |
  | "struct_time"             |                           |                           |
  +---------------------------+---------------------------+---------------------------+

このモジュールでは以下の関数とデータ型を定義します:

time.accept2dyear

   Boolean value indicating whether two-digit year values will be
   accepted.  This is true by default, but will be set to false if the
   environment variable "PYTHONY2K" has been set to a non-empty
   string.  It may also be modified at run time.

time.altzone

   ローカルの夏時間タイムゾーンにおける UTC からの時刻オフセットで、西
   に行くほど増加する、秒で表した値です (ほとんどの西ヨーロッパでは負
   になり、アメリカでは正、イギリスではゼロになります)。"daylight" が
   ゼロでないときのみ使用してください。

time.asctime([t])

   Convert a tuple or "struct_time" representing a time as returned by
   "gmtime()" or "localtime()" to a 24-character string of the
   following form: "'Sun Jun 20 23:21:05 1993'".  If *t* is not
   provided, the current time as returned by "localtime()" is used.
   Locale information is not used by "asctime()".

   注釈: Unlike the C function of the same name, there is no
     trailing newline.

   バージョン 2.1 で変更: Allowed *t* to be omitted.

time.clock()

   On Unix, return the current processor time as a floating point
   number expressed in seconds.  The precision, and in fact the very
   definition of the meaning of 「processor time」, depends on that of
   the C function of the same name, but in any case, this is the
   function to use for benchmarking Python or timing algorithms.

   Windows では、最初にこの関数が呼び出されてからの経過時間を wall-
   clock 秒で返します。この関数は Win32 関数
   "QueryPerformanceCounter()" に基づいていて、その精度は通常 1 マイク
   ロ秒以下です。

time.ctime([secs])

   エポックからの経過秒数で表現された時刻を、ローカルの時刻を表現する
   文字列に変換します。*secs* を指定しないか "None" を指定した場合、
   "time()" が返す値を現在の時刻として使用します。"ctime(secs)" は
   "asctime(localtime(secs))" と等価です。ローカル情報は "ctime()" に
   は使用されません。

   バージョン 2.1 で変更: Allowed *secs* to be omitted.

   バージョン 2.4 で変更: If *secs* is "None", the current time is
   used.

time.daylight

   DST タイムゾーンが定義されている場合ゼロでない値になります。

time.gmtime([secs])

   エポックからの経過時間で表現された時刻を、UTC で "struct_time" に変
   換します。このとき dst フラグは常にゼロとして扱われます。*secs* を
   指定しないか "None" を指定した場合、"time()" が返す値を現在の時刻と
   して使用します。秒の端数は無視されます。"struct_time" オブジェクト
   については前述の説明を参照してください。"calendar.timegm()" はこの
   関数と逆の変換を行います。

   バージョン 2.1 で変更: Allowed *secs* to be omitted.

   バージョン 2.4 で変更: If *secs* is "None", the current time is
   used.

time.localtime([secs])

   "gmtime()" に似ていますが、ローカル時間に変換します。*secs* を指定
   しないか "None" を指定した場合、"time()" が返す値を現在の時刻として
   使用します。DST が適用されている場合は dst フラグには "1" が設定さ
   れます。

   バージョン 2.1 で変更: Allowed *secs* to be omitted.

   バージョン 2.4 で変更: If *secs* is "None", the current time is
   used.

time.mktime(t)

   "localtime()" の逆を行う関数です。引数は "struct_time" か 9 個の要
   素すべての値を持つ完全なタプル (dst フラグも必要です; 時刻に DST が
   適用されるか不明の場合は "-1" を使用してください) で、UTC ではなく
   *ローカル* 時間を指定します。戻り値は "time()" との互換性のために浮
   動小数点数になります。入力した値を正しい時刻として表現できない場合
   、例外 "OverflowError" または "ValueError" が送出されます (どちらが
   送出されるかは、無効な値を受け取ったのが Python と下層の C ライブラ
   リのどちらなのかによって決まります)。この関数で時刻を生成できる最も
   古い日付はプラットフォームに依存します。

time.sleep(secs)

   Suspend execution of the current thread for the given number of
   seconds. The argument may be a floating point number to indicate a
   more precise sleep time. The actual suspension time may be less
   than that requested because any caught signal will terminate the
   "sleep()" following execution of that signal’s catching routine.
   Also, the suspension time may be longer than requested by an
   arbitrary amount because of the scheduling of other activity in the
   system.

time.strftime(format[, t])

   Convert a tuple or "struct_time" representing a time as returned by
   "gmtime()" or "localtime()" to a string as specified by the
   *format* argument.  If *t* is not provided, the current time as
   returned by "localtime()" is used.  *format* must be a string.
   "ValueError" is raised if any field in *t* is outside of the
   allowed range. "strftime()" returns a locale depedent byte string;
   the result may be converted to unicode by doing
   "strftime(<myformat>).decode(locale.getlocale()[1])".

   バージョン 2.1 で変更: Allowed *t* to be omitted.

   バージョン 2.4 で変更: "ValueError" raised if a field in *t* is out
   of range.

   バージョン 2.5 で変更: 0 is now a legal argument for any position
   in the time tuple; if it is normally illegal the value is forced to
   a correct one.

   *format* 文字列には以下のディレクティブ (指示語) を埋め込むことがで
   きます。これらはフィールド長や精度のオプションを付けずに表され、
   "strftime()" の結果の対応する文字列に置き換えられます:

   +-------------+----------------------------------+---------+
   | ディレクテ  | 意味                             | 注釈    |
   | ィブ        |                                  |         |
   +=============+==================================+=========+
   | "%a"        | ロケールの短縮された曜日名になり |         |
   |             | ます。                           |         |
   +-------------+----------------------------------+---------+
   | "%A"        | ロケールの曜日名になります。     |         |
   +-------------+----------------------------------+---------+
   | "%b"        | ロケールの短縮された月名になりま |         |
   |             | す。                             |         |
   +-------------+----------------------------------+---------+
   | "%B"        | ロケールの月名になります。       |         |
   +-------------+----------------------------------+---------+
   | "%c"        | ロケールの日時を適切な形式で表し |         |
   |             | ます。                           |         |
   +-------------+----------------------------------+---------+
   | "%d"        | 月中の日にちの 10 進表記になりま |         |
   |             | す [01,31]。                     |         |
   +-------------+----------------------------------+---------+
   | "%H"        | 時 (24 時間表記) の 10 進表記に  |         |
   |             | なります [00,23]。               |         |
   +-------------+----------------------------------+---------+
   | "%I"        | 時 (12 時間表記) の 10 進表記に  |         |
   |             | なります [01,12]。               |         |
   +-------------+----------------------------------+---------+
   | "%j"        | 年中の日にちの 10 進表記になりま |         |
   |             | す [001,366]。                   |         |
   +-------------+----------------------------------+---------+
   | "%m"        | 月の 10 進表記になります [01,12] |         |
   |             | 。                               |         |
   +-------------+----------------------------------+---------+
   | "%M"        | 分の 10 進表記になります [00,59] |         |
   |             | 。                               |         |
   +-------------+----------------------------------+---------+
   | "%p"        | ロケールの AM もしくは PM と等価 | (1)     |
   |             | な文字列になります。             |         |
   +-------------+----------------------------------+---------+
   | "%S"        | 秒の 10 進表記になります [00,61] | (2)     |
   |             | 。                               |         |
   +-------------+----------------------------------+---------+
   | "%U"        | Week number of the year (Sunday  | (3)     |
   |             | as the first day of the week) as |         |
   |             | a decimal number [00,53].  All   |         |
   |             | days in a new year preceding the |         |
   |             | first Sunday are considered to   |         |
   |             | be in week 0.                    |         |
   +-------------+----------------------------------+---------+
   | "%w"        | 曜日の 10 進表記になります [0 (  |         |
   |             | 日曜日),6]。                     |         |
   +-------------+----------------------------------+---------+
   | "%W"        | Week number of the year (Monday  | (3)     |
   |             | as the first day of the week) as |         |
   |             | a decimal number [00,53].  All   |         |
   |             | days in a new year preceding the |         |
   |             | first Monday are considered to   |         |
   |             | be in week 0.                    |         |
   +-------------+----------------------------------+---------+
   | "%x"        | ロケールの日付を適切な形式で表し |         |
   |             | ます。                           |         |
   +-------------+----------------------------------+---------+
   | "%X"        | ロケールの時間を適切な形式で表し |         |
   |             | ます。                           |         |
   +-------------+----------------------------------+---------+
   | "%y"        | 西暦の下 2 桁の 10 進表記になり  |         |
   |             | ます [00,99]。                   |         |
   +-------------+----------------------------------+---------+
   | "%Y"        | 西暦 ( 4桁) の 10 進表記を表しま |         |
   |             | す。                             |         |
   +-------------+----------------------------------+---------+
   | "%Z"        | タイムゾーンの名前を表します (タ |         |
   |             | イムゾーンがない場合には空文字列 |         |
   |             | )。                              |         |
   +-------------+----------------------------------+---------+
   | "%%"        | 文字 "'%'" を表します。          |         |
   +-------------+----------------------------------+---------+

   注釈:

   1. "strptime()" 関数で使う場合、"%p" ディレクティブが出力結果の
      時刻 フィールドに影響を及ぼすのは、時刻を解釈するために "%I" を
      使った ときのみです。

   2. The range really is "0" to "61"; this accounts for leap
      seconds and the (very rare) double leap seconds.

   3. "strptime()" 関数で使う場合、"%U" および "%W" を計算に使うの
      は曜 日と年を指定したときだけです。

   以下に **RFC 2822** インターネット電子メール標準で定義されている日
   付表現と互換の書式の例を示します。  [1]

      >>> from time import gmtime, strftime
      >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
      'Thu, 28 Jun 2001 14:17:15 +0000'

   一部のプラットフォームではさらにいくつかのディレクティブがサポート
   されていますが、標準 ANSI C で意味のある値はここで列挙したものだけ
   です。あなたのプラットフォームでサポートされている書式コードの全一
   覧については、*strftime(3)* のドキュメントを参照してください。

   一部のプラットフォームでは、フィールドの幅や精度を指定するオプショ
   ンがディレクティブの先頭の文字 "'%'" の直後に付けられるようになって
   いました; この機能も移植性はありません。フィールドの幅は通常 2 です
   が、"%j" は例外で 3 です。

time.strptime(string[, format])

   Parse a string representing a time according to a format.  The
   return  value is a "struct_time" as returned by "gmtime()" or
   "localtime()".

   The *format* parameter uses the same directives as those used by
   "strftime()"; it defaults to ""%a %b %d %H:%M:%S %Y"" which matches
   the formatting returned by "ctime()". If *string* cannot be parsed
   according to *format*, or if it has excess data after parsing,
   "ValueError" is raised. The default values used to fill in any
   missing data when more accurate values cannot be inferred are
   "(1900, 1, 1, 0, 0, 0, 0, 1, -1)".

   例えば:

   >>> import time
   >>> time.strptime("30 Nov 00", "%d %b %y")   # doctest: +NORMALIZE_WHITESPACE
   time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                    tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

   "%Z" ディレクティブへのサポートは "tzname" に収められている値と
   "daylight" が真かどうかで決められます。このため、常に既知の (かつ夏
   時間でないと考えられている) UTC や GMT を認識する時以外はプラットフ
   ォーム固有の動作になります。

   ドキュメント内で説明されているディレクティブだけがサポートされてい
   ます。"strftime()" はプラットフォームごとに実装されているので、説明
   されていないディレクティブも利用できるかもしれません。しかし、
   "strptime()" はプラットフォーム非依存なので、ドキュメント内でサポー
   トされているとされているディレクティブ以外は利用できません。

class time.struct_time

   "gmtime()", "localtime()" および "strptime()" が返す時刻値シーケン
   スの型です。これは名前付きタプル (*named tuple*) のインタフェースを
   もったオブジェクトです。値はインデックスでも属性名でもアクセス可能
   です。以下の値があります:

   +---------+---------------------+-----------------------------------+
   | インデ  | 属性                | 値                                |
   | ックス  |                     |                                   |
   +=========+=====================+===================================+
   | 0       | "tm_year"           | (例えば 1993)                     |
   +---------+---------------------+-----------------------------------+
   | 1       | "tm_mon"            | [1,12] の間の数                   |
   +---------+---------------------+-----------------------------------+
   | 2       | "tm_mday"           | [1,31] の間の数                   |
   +---------+---------------------+-----------------------------------+
   | 3       | "tm_hour"           | [0,23] の間の数                   |
   +---------+---------------------+-----------------------------------+
   | 4       | "tm_min"            | [0,59] の間の数                   |
   +---------+---------------------+-----------------------------------+
   | 5       | "tm_sec"            | [0,61] の間の数 "strftime()" の説 |
   |         |                     | 明にある **(2)** を読んで下さい   |
   +---------+---------------------+-----------------------------------+
   | 6       | "tm_wday"           | [0,6] の間の数、月曜が 0 になりま |
   |         |                     | す                                |
   +---------+---------------------+-----------------------------------+
   | 7       | "tm_yday"           | [1,366] の間の数                  |
   +---------+---------------------+-----------------------------------+
   | 8       | "tm_isdst"          | 0, 1 または -1; 以下を参照してく  |
   |         |                     | ださい                            |
   +---------+---------------------+-----------------------------------+

   バージョン 2.2 で追加.

   Note that unlike the C structure, the month value is a range of [1,
   12], not [0, 11].  A year value will be handled as described under
   Year 2000 (Y2K) issues above.

   "mktime()" の呼び出し時に、"tm_isdst" は夏時間が有効な場合は 1、そ
   うでない場合は 0 に設定されることがあります。 値が -1 の場合は夏時
   間について不明なことを表していて、普通 "tm_isdst" は正しい状態に設
   定されます。

   "struct_time" を引数とする関数に正しくない長さの "struct_time" や要
   素の型が正しくない "struct_time" を与えた場合には、 "TypeError" が
   送出されます。

time.time()

   Return the time in seconds since the epoch as a floating point
   number. Note that even though the time is always returned as a
   floating point number, not all systems provide time with a better
   precision than 1 second. While this function normally returns non-
   decreasing values, it can return a lower value than a previous call
   if the system clock has been set back between the two calls.

time.timezone

   (DST でない) ローカルタイムゾーンの UTC からの時刻オフセットで、西
   に行くほど増加する秒で表した値です (ほとんどの西ヨーロッパでは負に
   なり、アメリカでは正、イギリスではゼロになります)。

time.tzname

   二つの文字列からなるタプルです。最初の要素は DST でないローカルのタ
   イムゾーン名です。二つ目の要素は DST のタイムゾーンです。DST のタイ
   ムゾーンが定義されていない場合、二つ目の文字列を使うべきではありま
   せん。

time.tzset()

   Reset the time conversion rules used by the library routines. The
   environment variable "TZ" specifies how this is done. It will also
   set the variables "tzname" (from the "TZ" environment variable),
   "timezone" (non-DST seconds West of UTC), "altzone" (DST seconds
   west of UTC) and "daylight" (to 0 if this timezone does not have
   any daylight saving time rules, or to nonzero if there is a time,
   past, present or future when daylight saving time applies).

   バージョン 2.3 で追加.

   利用できる環境 : Unix 。

   注釈: 多くの場合、環境変数 "TZ" を変更すると、 "tzset()" を呼ばな
     い限り "localtime()" のような関数の出力に影響を及ぼすため、値が信
     頼でき なくなってしまいます。"TZ" 環境変数には空白文字を含めては
     なりませ ん。

   環境変数 "TZ" の標準的な書式は以下の通りです (分かりやすいように空
   白を入れています):

      std offset [dst [offset [,start[/time], end[/time]]]]

   各値は以下のようになっています:

   "std" と "dst"
      三文字またはそれ以上の英数字で、タイムゾーンの略称を与えます。こ
      の値は time.tzname になります。

   "offset"
      オフセットは形式: "± hh[:mm[:ss]]" をとります。この表現は、UTC
      時刻にするためにローカルな時間に加算する必要のある時間値を示しま
      す。』-『 が先頭につく場合、そのタイムゾーンは本初子午線 (Prime
      Meridian) より東側にあります。それ以外の場合は本初子午線の西側で
      す。オフセットが dst の後ろに続かない場合、夏時間は標準時より一
      時間先行しているものと仮定します。

   "start[/time], end[/time]"
      いつ DST に移動し、DST から戻ってくるかを示します。開始および終
      了日時の形式は以下のいずれかです:

      "J*n*"
         ユリウス日 (Julian day) *n* (1 <= *n* <= 365) を表します。う
         るう日は計算に含められないため、2 月 28 日は常に 59 で、3 月
         1 日は 60 になります。

      "*n*"
         ゼロから始まるユリウス日 (0 <= *n* <= 365) です。うるう日は計
         算に含められるため、2 月 29 日を参照することができます。

      "M*m*.*n*.*d*"
         The *d*’th day (0 <= *d* <= 6) or week *n* of month *m* of
         the year (1 <= *n* <= 5, 1 <= *m* <= 12, where week 5 means
         「the last *d* day in month *m*」 which may occur in either
         the fourth or the fifth week). Week 1 is the first week in
         which the *d*’th day occurs. Day zero is Sunday.

      "time" は "offset" とほぼ同じで、先頭に符号 (『-『 や 『+』) を
      付けてはいけないところだけが違います。時刻が指定されていなければ
      、デフォルトの値 02:00:00 になります。

      >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
      >>> time.tzset()
      >>> time.strftime('%X %x %Z')
      '02:07:36 05/08/03 EDT'
      >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
      >>> time.tzset()
      >>> time.strftime('%X %x %Z')
      '16:08:12 05/08/03 AEST'

   多くの Unix システム (*BSD, Linux, Solaris, および Darwin を含む)
   では、システムの zoneinfo (*tzfile(5)*) データベースを使ったほうが
   、タイムゾーンごとの規則を指定する上で便利です。これを行うには、必
   要なタイムゾーンデータファイルへのパスをシステムの 『zoneinfo』 タ
   イムゾーンデータベースからの相対で表した値を環境変数 "TZ" に設定し
   ます。システムの 『zoneinfo』 は通常 "/usr/share/zoneinfo" にありま
   す。例えば、 "'US/Eastern'" 、 "'Australia/Melbourne'" 、 "'Egypt'"
   ないし "'Europe/Amsterdam'" と指定します。

      >>> os.environ['TZ'] = 'US/Eastern'
      >>> time.tzset()
      >>> time.tzname
      ('EST', 'EDT')
      >>> os.environ['TZ'] = 'Egypt'
      >>> time.tzset()
      >>> time.tzname
      ('EET', 'EEST')

参考:

  "datetime" モジュール
     日付と時刻に対する、よりオブジェクト指向のインタフェースです。

  "locale" モジュール
     国際化サービスです。ロケールの設定は "strftime()" および
     "strptime()" の多くの書式指定子の解釈に影響を及ぼします。

  "calendar" モジュール
     一般的なカレンダーに関する関数群です。"timegm()" はこのモジュール
     の "gmtime()" の逆を行う関数です。

-[ 脚注 ]-

[1] "%Z" の使用は現在非推奨です。ただし、ここで実現したい時間およ
    び分 オフセットへの展開を行ってくれる "%z" エスケープはすべての
    ANSI C ライブラリでサポートされているわけではありません。また、
    1982 年に 提出されたオリジナルの **RFC 822** 標準では西暦の表現を
    2 桁とする よう要求している (%Y でなく%y ) ものの、実際には 2000
    年になるだい ぶ以前から 4 桁の西暦表現に移行しています。その後
    **RFC 822** は撤 廃され、4 桁の西暦表現は **RFC 1123** で初めて勧
    告され、**RFC 2822** において義務付けられました。
