このモジュールは常に利用可能ですが、すべての関数がすべてのプラットフォームで利用可能なわけではありません。このモジュールで定義されているほとんどの関数は、プラットフォーム上の同名の C ライブラリ関数を呼び出します。これらの関数に対する意味付けはプラットフォーム間で異なるため、プラットフォーム提供のドキュメントを読んでおくと便利でしょう。
時間の表現を変換するには、以下の関数を利用してください:
エポックからの秒数
UTC の
struct_time
gmtime()
エポックからの秒数
ローカル時間の
struct_time
localtime()
UTC の
struct_time
エポックからの秒数
calendar.timegm()
ローカル時間の
struct_time
エポックからの秒数
mktime()
time.
asctime
(
[
t
]
)
Convert a tuple or
struct_time
representing a time as returned by
gmtime()
or
localtime()
to a string of the following
form:
'Sun
Jun
20
23:21:05
1993'
. The day field is two characters long
and is space padded if the day is a single digit,
e.g.:
'Wed
Jun
9
04:26:40
1993'
.
If
t
is not provided, the current time as returned by
localtime()
is used. Locale information is not used by
asctime()
.
同名の C の関数と違って、
asctime()
は末尾に改行文字を加えません。
time.
pthread_getcpuclockid
(
thread_id
)
Return the
clk_id
of the thread-specific CPU-time clock for the specified
thread_id
.
Use
threading.get_ident()
or the
ident
attribute of
threading.Thread
objects to get a suitable value
for
thread_id
.
Passing an invalid or expired
thread_id
may result in
undefined behavior, such as segmentation fault.
利用可能な環境
: Unix
更なる情報については
pthread_getcpuclockid(3)
の man を参照してください。
Added in version 3.7.
time.
clock_getres
(
clk_id
)
指定された
clk_id
クロックの分解能(精度)を返します。
clk_id
として受け付けられる値の一覧は
Clock ID Constants
を参照してください。
利用可能な環境
: Unix。
Added in version 3.3.
time.
clock_gettime
(
clk_id
)
→
float
指定された
clk_id
クロックの時刻を返します。
clk_id
として受け付けられる値の一覧は
Clock ID Constants
を参照してください。
Use
clock_gettime_ns()
to avoid the precision loss caused by the
float
type.
利用可能な環境
: Unix。
Added in version 3.3.
time.
clock_settime
(
clk_id
,
time
:
float
)
指定された
clk_id
クロックの時刻を設定します。
現在、
CLOCK_REALTIME
は
clk_id
が受け付ける唯一の値です。
Use
clock_settime_ns()
to avoid the precision loss caused by the
float
type.
利用可能な環境
: Unix。
Added in version 3.3.
time.
ctime
(
[
secs
]
)
Convert a time expressed in seconds since the
epoch
to a string of a form:
'Sun
Jun
20
23:21:05
1993'
representing local time. The day field
is two characters long and is space padded if the day is a single digit,
e.g.:
'Wed
Jun
9
04:26:40
1993'
.
secs
を指定しないか
None
を指定した場合、
time()
が返す値を現在の時刻として使用します。
ctime(secs)
は
asctime(localtime(secs))
と等価です。ローカル情報は
ctime()
には使用されません。
time.
get_clock_info
(
name
)
指定されたクロックの情報を名前空間オブジェクトとして取得します。サポートされているクロック名およびそれらの値を取得する関数は以下の通りです:
'monotonic'
:
time.monotonic()
'perf_counter'
:
time.perf_counter()
'process_time'
:
time.process_time()
'thread_time'
:
time.thread_time()
'time'
:
time.time()
結果は以下の属性をもちます:
adjustable
: 自動 (NTP デーモンによるなど) またはシステム管理者による手動で変更できる場合は
True
、それ以外の場合は
False
になります。
implementation
: クロック値を取得するために内部で使用している C 関数の名前です。
使える値については
Clock ID Constants
を参照してください。
monotonic
: クロック値が後戻りすることがない場合
True
が、そうでない場合は
False
になります。
resolution
: クロックの分解能を秒 (
float
) で表します。
Added in version 3.3.
time.
localtime
(
[
secs
]
)
gmtime()
に似ていますが、ローカル時間に変換します。
secs
を指定しないか
None
を指定した場合、
time()
が返す値を現在の時刻として使用します。DST が適用されている場合は dst フラグには
1
が設定されます。
localtime()
may raise
OverflowError
, if the timestamp is
outside the range of values supported by the platform C
localtime()
or
gmtime()
functions, and
OSError
on
localtime()
or
gmtime()
failure. It's common for this to be restricted to years
between 1970 and 2038.
time.
mktime
(
t
)
This is the inverse function of
localtime()
. Its argument is the
struct_time
or full 9-tuple (since the dst flag is needed; use
-1
as the dst flag if it is unknown) which expresses the time in
local
time, not
UTC. It returns a floating-point number, for compatibility with
time()
.
If the input value cannot be represented as a valid time, either
OverflowError
or
ValueError
will be raised (which depends on
whether the invalid value is caught by Python or the underlying C libraries).
The earliest date for which it can generate a time is platform-dependent.
time.
monotonic
(
)
→
float
モノトニッククロック、すなわち後戻りしないクロックの値を (小数秒で) 返します。このクロックはシステムクロックの更新の影響を受けません。戻り値の基準点は定義されていないので、二回の呼び出しの結果の差だけが有効です。
Use
monotonic_ns()
to avoid the precision loss caused by the
float
type.
Added in version 3.3.
バージョン 3.5 で変更:
この関数は、常に利用でき、常にシステム全域で使えるようになりました。
バージョン 3.10 で変更:
On macOS, the function is now system-wide.
time.
perf_counter
(
)
→
float
パフォーマンスカウンター、すなわち短い時間を計測するための可能な限り高い分解能を持つクロックの値を (小数秒で) 返します。これはスリープ中の経過時間を含み、システムワイドです。戻り値の基準点は定義されていないので、二回の呼び出しの結果の差だけが有効です。
Use
perf_counter_ns()
to avoid the precision loss caused by the
float
type.
Added in version 3.3.
バージョン 3.10 で変更:
On Windows, the function is now system-wide.
time.
process_time
(
)
→
float
現在のプロセスのシステムおよびユーザー CPU 時間の値を (小数秒で) 返します。これはスリープ中の経過時間を含みません。これは定義上プロセスワイドです。戻り値の基準点は定義されていないので、二回の呼び出しの結果の差だけが有効です。
Use
process_time_ns()
to avoid the precision loss caused by the
float
type.
Added in version 3.3.
time.
sleep
(
secs
)
Suspend execution of the calling thread for the given number of seconds.
The argument may be a floating-point number to indicate a more precise sleep
time.
If the sleep is interrupted by a signal and no exception is raised by the
signal handler, the sleep is restarted with a recomputed timeout.
The suspension time may be longer than requested by an arbitrary amount,
because of the scheduling of other activity in the system.
On Windows, if
secs
is zero, the thread relinquishes the remainder of its
time slice to any other thread that is ready to run. If there are no other
threads ready to run, the function returns immediately, and the thread
continues execution. On Windows 8.1 and newer the implementation uses
a
high-resolution timer
which provides resolution of 100 nanoseconds. If
secs
is zero,
Sleep(0)
is used.
Unix implementation:
Use
clock_nanosleep()
if available (resolution: 1 nanosecond);
Or use
nanosleep()
if available (resolution: 1 nanosecond);
Or use
select()
(resolution: 1 microsecond).
バージョン 3.5 で変更:
スリープがシグナルに中断されてもシグナルハンドラが例外を送出しない限り、少なくとも
secs
だけスリープするようになりました (論拠については
PEP 475
を参照してください)。
バージョン 3.11 で変更:
On Unix, the
clock_nanosleep()
and
nanosleep()
functions are now
used if available. On Windows, a waitable timer is now used.
time.
strftime
(
format
[
,
t
]
)
gmtime()
や
localtime()
が返す時刻値タプルまたは
struct_time
を、
format
で指定した文字列形式に変換します。
t
が与えられていない場合、
localtime()
が返す値を現在の時刻として使用します。
format
は文字列でなくてはなりません。
t
のいずれかのフィールドが許容範囲外の数値であった場合、
ValueError
を送出します。
0 は時刻タプル内のいずれの位置の引数にも使用できます; それが一般に不正な値であれば、正しい値に強制的に置き換えられます。
format
文字列には以下のディレクティブ (指示語) を埋め込むことができます。これらはフィールド長や精度のオプションを付けずに表され、
strftime()
の結果の対応する文字列に置き換えられます:
ディレクティブ
ロケールの短縮された曜日名になります。
ロケールの曜日名になります。
ロケールの短縮された月名になります。
ロケールの月名になります。
ロケールの日時を適切な形式で表します。
月中の日にちの 10 進表記になります [01,31]。
Microseconds as a decimal number
[000000,999999].
時 (24 時間表記) の 10 進表記になります [00,23]。
時 (12 時間表記) の 10 進表記になります [01,12]。
年中の日にちの 10 進表記になります [001,366]。
月の 10 進表記になります [01,12]。
分の 10 進表記になります [00,59]。
ロケールの AM もしくは PM と等価な文字列になります。
秒の 10 進表記になります [00,61]。
年の初めから何週目か (日曜を週の始まりとします) を表す 10 進数になります [00,53]。年が明けてから最初の日曜日までのすべての曜日は 0 週目に属すると見なされます。
曜日の 10 進表記になります [0 (日曜日),6]。
年の初めから何週目か (月曜を週の始まりとします) を表す 10 進数になります [00,53]。年が明けてから最初の月曜日までの全ての曜日は 0 週目に属すると見なされます。
ロケールの日付を適切な形式で表します。
ロケールの時間を適切な形式で表します。
西暦の下 2 桁の 10 進表記になります [00,99]。
西暦 ( 4桁) の 10 進表記を表します。
タイムゾーンと UTC/GMT との時差を表す正または負の時間を +HHMM、-HHMM で表します。H は時間の、M は分の 10 進表記になります [-23:59, +23:59]。
タイムゾーンの名前を表します (タイムゾーンがない場合には空文字列)。非推奨です。
文字
'%'
を表します。
The
%f
format directive only applies to
strptime()
,
not to
strftime()
. However, see also
datetime.datetime.strptime()
and
datetime.datetime.strftime()
where the
%f
format directive
applies to microseconds
.
strptime()
関数で使う場合、
%p
ディレクティブが出力結果の時刻フィールドに影響を及ぼすのは、時刻を解釈するために
%I
を使ったときのみです。
値の幅は実際に
0
から
61
です;
60
は
うるう秒<leap seconds>
を表し、
61
は歴史的理由によりサポートされています。
strptime()
関数で使う場合、
%U
および
%W
を計算に使うのは曜日と年を指定したときだけです。
以下に
RFC 2822
インターネット電子メール標準で定義されている日付表現と互換の書式の例を示します。
>>> 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])
時刻を表現する文字列を書式に従って解釈します。返される値は gmtime()
や localtime()
が返すような struct_time
です。
format パラメーターは strftime()
で使うものと同じディレクティブを使います; このパラメーターの値はデフォルトでは "%a %b %d %H:%M:%S %Y"
で、ctime()
が返すフォーマットに一致します。string が format に従って解釈できなかった場合、例外 ValueError
が送出されます。解析しようとする string が解析後に余分なデータを持っていた場合、ValueError
が送出されます。欠落したデータについて、適切な値を推測できない場合はデフォルトの値で埋められ、その値は (1900, 1, 1, 0, 0, 0, 0, 1, -1)
です。string も format も文字列でなければなりません。
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")
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()
が返す時刻値シーケンスの型です。これは 名前付きタプル のインターフェースをもったオブジェクトです。値はインデックスでも属性名でもアクセス可能です。以下の値があります:
インデックス
tm_year
(例えば 1993)
tm_mon
[1,12] の間の数
tm_mday
[1,31] の間の数
tm_hour
[0,23] の間の数
tm_min
[0,59] の間の数
tm_sec
range [0, 61]; see Note (2) in strftime()
tm_wday
range [0, 6]; Monday is 0
tm_yday
[1,366] の間の数
tm_isdst
0, 1 または -1; 以下を参照してください
tm_zone
タイムゾーンの短縮名
tm_gmtoff
UTC から東方向へのオフセット (秒)
C の構造体とは異なり、月の値は [0, 11] ではなく [1, 12] であることに注意してください。
mktime()
の呼び出し時に、tm_isdst
は夏時間が有効な場合は 1、そうでない場合は 0 に設定されることがあります。
値が -1 の場合は夏時間について不明なことを表していて、普通 tm_isdst
は正しい状態に設定されます。
struct_time
を引数とする関数に正しくない長さの struct_time
や要素の型が正しくない struct_time
を与えた場合には、 TypeError
が送出されます。
time.time() → float
Return the time in seconds since the epoch as a floating-point
number. The handling of leap seconds is platform dependent.
On Windows and most Unix systems, the leap seconds are not counted towards
the time in seconds since the epoch. This is commonly referred to as Unix
time.
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()
が返す数値は、 gmtime()
関数に渡されて UTC の、あるいは localtime()
関数に渡されて現地時間の、より一般的な時間のフォーマット (つまり、年、月、日、時間など) に変換されているかもしれません。
どちらの場合でも struct_time
オブジェクトが返され、このオブジェクトの属性としてカレンダー日付の構成要素へアクセスできます。
Use time_ns()
to avoid the precision loss caused by the float
type.
time.thread_time() → float
現在のスレッドのシステムおよびユーザー CPU 時間の値を (小数秒で) 返します。これはスリープ中の経過時間を含みません。これは定義上スレッド固有です。戻り値の基準点は定義されていないので、同一スレッドにおける二回の呼び出しの結果の差だけが有効です。
Use thread_time_ns()
to avoid the precision loss caused by the
float
type.
Availability: Linux, Unix, Windows.
Unix systems supporting CLOCK_THREAD_CPUTIME_ID
.
Added in version 3.7.
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).
利用可能な環境: 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 から戻ってくるかを示します。開始および終了日時の形式は以下のいずれかです:
Jn
ユリウス日 (Julian day) n (1 <= n <= 365) を表します。うるう日は計算に含められないため、2 月 28 日は常に 59 で、3 月 1 日は 60 になります。
n
ゼロから始まるユリウス日 (0 <= n <= 365) です。うるう日は計算に含められるため、2 月 29 日を参照することができます。
Mm.n.d
m 月の週 n における d 番目の日 (0 <= d <= 6, 1 <= n <= 5, 1 <= m <= 12) を表します。週 5 は月 m における最終週の d 番目の日を表し、第 4 週か第 5 週のどちらかになります。週 1 は日 d が最初に現れる日を指します。日 0 は日曜日です。
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')
Clock ID Constants
These constants are used as parameters for clock_getres()
and
clock_gettime()
.
time.CLOCK_BOOTTIME
Identical to CLOCK_MONOTONIC
, except it also includes any time that
the system is suspended.
This allows applications to get a suspend-aware monotonic clock without
having to deal with the complications of CLOCK_REALTIME
, which may
have discontinuities if the time is changed using settimeofday()
or
similar.
利用可能な環境: Linux 2.6.39以上。
Added in version 3.7.
time.CLOCK_HIGHRES
Solaris OS は任意のハードウェアソースの使用を試み、ナノ秒レベルの分解能を提供する CLOCK_HIGHRES
タイマーを具備しています。CLOCK_HIGHRES
は変更不可で、高分解能のクロックです。
利用可能な環境: Solaris。
Added in version 3.3.
time.CLOCK_MONOTONIC_RAW
CLOCK_MONOTONIC
と似ていますが、NTP の影響を受けていない、ハードウェアベースの時刻へのアクセスを提供します。
Availability: Linux >= 2.6.28, macOS >= 10.12.
Added in version 3.3.
time.CLOCK_TAI
International Atomic Time
The system must have a current leap second table in order for this to give
the correct answer. PTP or NTP software can maintain a leap second table.
利用可能な環境: Linux。
Added in version 3.9.
time.CLOCK_UPTIME
Time whose absolute value is the time the system has been running and not
suspended, providing accurate uptime measurement, both absolute and
interval.
Availability: FreeBSD, OpenBSD >= 5.5.
Added in version 3.7.
time.CLOCK_UPTIME_RAW
Clock that increments monotonically, tracking the time since an arbitrary
point, unaffected by frequency or time adjustments and not incremented while
the system is asleep.
Availability: macOS >= 10.12.
Added in version 3.8.
The following constant is the only parameter that can be sent to
clock_settime()
.
time.CLOCK_REALTIME
システム全体のリアルタイムクロックです。このクロックを設定するには適切な権限が必要です。
利用可能な環境: Unix。
Added in version 3.3.
For the above Timezone constants (altzone
, daylight
, timezone
,
and tzname
), the value is determined by the timezone rules in effect
at module load time or the last time tzset()
is called and may be incorrect
for times in the past. It is recommended to use the tm_gmtoff
and
tm_zone
results from localtime()
to obtain timezone information.
datetime
モジュール日付と時刻に対する、よりオブジェクト指向のインターフェースです。
locale
モジュール国際化サービスです。ロケールの設定は strftime()
および strptime()
の多くの書式指定子の解釈に影響を及ぼします。
calendar
モジュール一般的なカレンダーに関する関数群です。timegm()
はこのモジュールの gmtime()
の逆を行う関数です。
[1]
(1,2,3)
%Z
の使用は現在非推奨です。ただし、ここで実現したい時間および分オフセットへの展開を行ってくれる %z
エスケープはすべての ANSI C ライブラリでサポートされているわけではありません。また、1982 年に提出されたオリジナルの RFC 822 標準では西暦の表現を 2 桁とするよう要求している (%Y
でなく %y
) ものの、実際には 2000 年になるだいぶ以前から 4 桁の西暦表現に移行しています。その後 RFC 822 は撤廃され、4 桁の西暦表現は RFC 1123 で初めて勧告され、RFC 2822 において義務付けられました。
2001-2024, Python Software Foundation.
This page is licensed under the Python Software Foundation License Version 2.
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
See History and License for more information.