blob: ceae8fa29c2b0363d08562726155c1e4dc227fbd [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`time` --- Time access and conversions
2===========================================
3
4.. module:: time
5 :synopsis: Time access and conversions.
6
7
8This module provides various time-related functions. For related
9functionality, see also the :mod:`datetime` and :mod:`calendar` modules.
10
11Although this module is always available,
12not all functions are available on all platforms. Most of the functions
13defined in this module call platform C library functions with the same name. It
14may sometimes be helpful to consult the platform documentation, because the
15semantics of these functions varies among platforms.
16
17An explanation of some terminology and conventions is in order.
18
19 .. index:: single: epoch
20
21* The :dfn:`epoch` is the point where the time starts. On January 1st of that
22 year, at 0 hours, the "time since the epoch" is zero. For Unix, the epoch is
23 1970. To find out what the epoch is, look at ``gmtime(0)``.
24
25 .. index:: single: Year 2038
26
27* The functions in this module do not handle dates and times before the epoch or
28 far in the future. The cut-off point in the future is determined by the C
29 library; for Unix, it is typically in 2038.
30
31 .. index::
32 single: Year 2000
33 single: Y2K
34
35* **Year 2000 (Y2K) issues**: Python depends on the platform's C library, which
36 generally doesn't have year 2000 issues, since all dates and times are
37 represented internally as seconds since the epoch. Functions accepting a
38 :class:`struct_time` (see below) generally require a 4-digit year. For backward
39 compatibility, 2-digit years are supported if the module variable
40 ``accept2dyear`` is a non-zero integer; this variable is initialized to ``1``
41 unless the environment variable :envvar:`PYTHONY2K` is set to a non-empty
42 string, in which case it is initialized to ``0``. Thus, you can set
43 :envvar:`PYTHONY2K` to a non-empty string in the environment to require 4-digit
44 years for all year input. When 2-digit years are accepted, they are converted
45 according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999,
46 and values 0--68 are mapped to 2000--2068. Values 100--1899 are always illegal.
47 Note that this is new as of Python 1.5.2(a2); earlier versions, up to Python
48 1.5.1 and 1.5.2a1, would add 1900 to year values below 1900.
49
50 .. index::
51 single: UTC
52 single: Coordinated Universal Time
53 single: Greenwich Mean Time
54
55* UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or
56 GMT). The acronym UTC is not a mistake but a compromise between English and
57 French.
58
59 .. index:: single: Daylight Saving Time
60
61* DST is Daylight Saving Time, an adjustment of the timezone by (usually) one
62 hour during part of the year. DST rules are magic (determined by local law) and
63 can change from year to year. The C library has a table containing the local
64 rules (often it is read from a system file for flexibility) and is the only
65 source of True Wisdom in this respect.
66
67* The precision of the various real-time functions may be less than suggested by
68 the units in which their value or argument is expressed. E.g. on most Unix
Georg Brandlc575c902008-09-13 17:46:05 +000069 systems, the clock "ticks" only 50 or 100 times a second.
Georg Brandl116aa622007-08-15 14:28:22 +000070
71* On the other hand, the precision of :func:`time` and :func:`sleep` is better
72 than their Unix equivalents: times are expressed as floating point numbers,
73 :func:`time` returns the most accurate time available (using Unix
74 :cfunc:`gettimeofday` where available), and :func:`sleep` will accept a time
75 with a nonzero fraction (Unix :cfunc:`select` is used to implement this, where
76 available).
77
78* The time value as returned by :func:`gmtime`, :func:`localtime`, and
79 :func:`strptime`, and accepted by :func:`asctime`, :func:`mktime` and
80 :func:`strftime`, is a sequence of 9 integers. The return values of
81 :func:`gmtime`, :func:`localtime`, and :func:`strptime` also offer attribute
82 names for individual fields.
83
84 +-------+------------------+------------------------------+
85 | Index | Attribute | Values |
86 +=======+==================+==============================+
87 | 0 | :attr:`tm_year` | (for example, 1993) |
88 +-------+------------------+------------------------------+
89 | 1 | :attr:`tm_mon` | range [1,12] |
90 +-------+------------------+------------------------------+
91 | 2 | :attr:`tm_mday` | range [1,31] |
92 +-------+------------------+------------------------------+
93 | 3 | :attr:`tm_hour` | range [0,23] |
94 +-------+------------------+------------------------------+
95 | 4 | :attr:`tm_min` | range [0,59] |
96 +-------+------------------+------------------------------+
97 | 5 | :attr:`tm_sec` | range [0,61]; see **(1)** in |
98 | | | :func:`strftime` description |
99 +-------+------------------+------------------------------+
100 | 6 | :attr:`tm_wday` | range [0,6], Monday is 0 |
101 +-------+------------------+------------------------------+
102 | 7 | :attr:`tm_yday` | range [1,366] |
103 +-------+------------------+------------------------------+
104 | 8 | :attr:`tm_isdst` | 0, 1 or -1; see below |
105 +-------+------------------+------------------------------+
106
107 Note that unlike the C structure, the month value is a range of 1-12, not 0-11.
108 A year value will be handled as described under "Year 2000 (Y2K) issues" above.
109 A ``-1`` argument as the daylight savings flag, passed to :func:`mktime` will
110 usually result in the correct daylight savings state to be filled in.
111
112 When a tuple with an incorrect length is passed to a function expecting a
113 :class:`struct_time`, or having elements of the wrong type, a :exc:`TypeError`
114 is raised.
115
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000116* Use the following functions to convert between time representations:
117
118 +-------------------------+-------------------------+-------------------------+
119 | From | To | Use |
120 +=========================+=========================+=========================+
121 | seconds since the epoch | :class:`struct_time` in | :func:`gmtime` |
122 | | UTC | |
123 +-------------------------+-------------------------+-------------------------+
124 | seconds since the epoch | :class:`struct_time` in | :func:`localtime` |
125 | | local time | |
126 +-------------------------+-------------------------+-------------------------+
127 | :class:`struct_time` in | seconds since the epoch | :func:`calendar.timegm` |
128 | UTC | | |
129 +-------------------------+-------------------------+-------------------------+
130 | :class:`struct_time` in | seconds since the epoch | :func:`mktime` |
131 | local time | | |
132 +-------------------------+-------------------------+-------------------------+
133
134
Georg Brandl116aa622007-08-15 14:28:22 +0000135The module defines the following functions and data items:
136
137
138.. data:: accept2dyear
139
140 Boolean value indicating whether two-digit year values will be accepted. This
141 is true by default, but will be set to false if the environment variable
142 :envvar:`PYTHONY2K` has been set to a non-empty string. It may also be modified
143 at run time.
144
145
146.. data:: altzone
147
148 The offset of the local DST timezone, in seconds west of UTC, if one is defined.
149 This is negative if the local DST timezone is east of UTC (as in Western Europe,
150 including the UK). Only use this if ``daylight`` is nonzero.
151
152
153.. function:: asctime([t])
154
155 Convert a tuple or :class:`struct_time` representing a time as returned by
156 :func:`gmtime` or :func:`localtime` to a 24-character string of the following
157 form: ``'Sun Jun 20 23:21:05 1993'``. If *t* is not provided, the current time
158 as returned by :func:`localtime` is used. Locale information is not used by
159 :func:`asctime`.
160
161 .. note::
162
163 Unlike the C function of the same name, there is no trailing newline.
164
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166.. function:: clock()
167
168 .. index::
169 single: CPU time
170 single: processor time
171 single: benchmarking
172
173 On Unix, return the current processor time as a floating point number expressed
174 in seconds. The precision, and in fact the very definition of the meaning of
175 "processor time", depends on that of the C function of the same name, but in any
176 case, this is the function to use for benchmarking Python or timing algorithms.
177
178 On Windows, this function returns wall-clock seconds elapsed since the first
179 call to this function, as a floating point number, based on the Win32 function
180 :cfunc:`QueryPerformanceCounter`. The resolution is typically better than one
181 microsecond.
182
183
184.. function:: ctime([secs])
185
186 Convert a time expressed in seconds since the epoch to a string representing
187 local time. If *secs* is not provided or :const:`None`, the current time as
188 returned by :func:`time` is used. ``ctime(secs)`` is equivalent to
189 ``asctime(localtime(secs))``. Locale information is not used by :func:`ctime`.
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192.. data:: daylight
193
194 Nonzero if a DST timezone is defined.
195
196
197.. function:: gmtime([secs])
198
199 Convert a time expressed in seconds since the epoch to a :class:`struct_time` in
200 UTC in which the dst flag is always zero. If *secs* is not provided or
201 :const:`None`, the current time as returned by :func:`time` is used. Fractions
202 of a second are ignored. See above for a description of the
203 :class:`struct_time` object. See :func:`calendar.timegm` for the inverse of this
204 function.
205
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207.. function:: localtime([secs])
208
209 Like :func:`gmtime` but converts to local time. If *secs* is not provided or
210 :const:`None`, the current time as returned by :func:`time` is used. The dst
211 flag is set to ``1`` when DST applies to the given time.
212
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214.. function:: mktime(t)
215
216 This is the inverse function of :func:`localtime`. Its argument is the
217 :class:`struct_time` or full 9-tuple (since the dst flag is needed; use ``-1``
218 as the dst flag if it is unknown) which expresses the time in *local* time, not
219 UTC. It returns a floating point number, for compatibility with :func:`time`.
220 If the input value cannot be represented as a valid time, either
221 :exc:`OverflowError` or :exc:`ValueError` will be raised (which depends on
222 whether the invalid value is caught by Python or the underlying C libraries).
223 The earliest date for which it can generate a time is platform-dependent.
224
225
226.. function:: sleep(secs)
227
228 Suspend execution for the given number of seconds. The argument may be a
229 floating point number to indicate a more precise sleep time. The actual
230 suspension time may be less than that requested because any caught signal will
231 terminate the :func:`sleep` following execution of that signal's catching
232 routine. Also, the suspension time may be longer than requested by an arbitrary
233 amount because of the scheduling of other activity in the system.
234
235
236.. function:: strftime(format[, t])
237
238 Convert a tuple or :class:`struct_time` representing a time as returned by
239 :func:`gmtime` or :func:`localtime` to a string as specified by the *format*
240 argument. If *t* is not provided, the current time as returned by
241 :func:`localtime` is used. *format* must be a string. :exc:`ValueError` is
242 raised if any field in *t* is outside of the allowed range.
243
Georg Brandl55ac8f02007-09-01 13:51:09 +0000244 0 is a legal argument for any position in the time tuple; if it is normally
245 illegal the value is forced to a correct one.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247 The following directives can be embedded in the *format* string. They are shown
248 without the optional field width and precision specification, and are replaced
249 by the indicated characters in the :func:`strftime` result:
250
Georg Brandl55ac8f02007-09-01 13:51:09 +0000251 +-----------+------------------------------------------------+-------+
252 | Directive | Meaning | Notes |
253 +===========+================================================+=======+
254 | ``%a`` | Locale's abbreviated weekday name. | |
255 | | | |
256 +-----------+------------------------------------------------+-------+
257 | ``%A`` | Locale's full weekday name. | |
258 +-----------+------------------------------------------------+-------+
259 | ``%b`` | Locale's abbreviated month name. | |
260 | | | |
261 +-----------+------------------------------------------------+-------+
262 | ``%B`` | Locale's full month name. | |
263 +-----------+------------------------------------------------+-------+
264 | ``%c`` | Locale's appropriate date and time | |
265 | | representation. | |
266 +-----------+------------------------------------------------+-------+
267 | ``%d`` | Day of the month as a decimal number [01,31]. | |
268 | | | |
269 +-----------+------------------------------------------------+-------+
270 | ``%H`` | Hour (24-hour clock) as a decimal number | |
271 | | [00,23]. | |
272 +-----------+------------------------------------------------+-------+
273 | ``%I`` | Hour (12-hour clock) as a decimal number | |
274 | | [01,12]. | |
275 +-----------+------------------------------------------------+-------+
276 | ``%j`` | Day of the year as a decimal number [001,366]. | |
277 | | | |
278 +-----------+------------------------------------------------+-------+
279 | ``%m`` | Month as a decimal number [01,12]. | |
280 | | | |
281 +-----------+------------------------------------------------+-------+
282 | ``%M`` | Minute as a decimal number [00,59]. | |
283 | | | |
284 +-----------+------------------------------------------------+-------+
285 | ``%p`` | Locale's equivalent of either AM or PM. | \(1) |
286 | | | |
287 +-----------+------------------------------------------------+-------+
288 | ``%S`` | Second as a decimal number [00,61]. | \(2) |
289 | | | |
290 +-----------+------------------------------------------------+-------+
291 | ``%U`` | Week number of the year (Sunday as the first | \(3) |
292 | | day of the week) as a decimal number [00,53]. | |
293 | | All days in a new year preceding the first | |
294 | | Sunday are considered to be in week 0. | |
295 | | | |
296 | | | |
297 | | | |
298 +-----------+------------------------------------------------+-------+
299 | ``%w`` | Weekday as a decimal number [0(Sunday),6]. | |
300 | | | |
301 +-----------+------------------------------------------------+-------+
302 | ``%W`` | Week number of the year (Monday as the first | \(3) |
303 | | day of the week) as a decimal number [00,53]. | |
304 | | All days in a new year preceding the first | |
305 | | Monday are considered to be in week 0. | |
306 | | | |
307 | | | |
308 | | | |
309 +-----------+------------------------------------------------+-------+
310 | ``%x`` | Locale's appropriate date representation. | |
311 | | | |
312 +-----------+------------------------------------------------+-------+
313 | ``%X`` | Locale's appropriate time representation. | |
314 | | | |
315 +-----------+------------------------------------------------+-------+
316 | ``%y`` | Year without century as a decimal number | |
317 | | [00,99]. | |
318 +-----------+------------------------------------------------+-------+
319 | ``%Y`` | Year with century as a decimal number. | |
320 | | | |
321 +-----------+------------------------------------------------+-------+
322 | ``%Z`` | Time zone name (no characters if no time zone | |
323 | | exists). | |
324 +-----------+------------------------------------------------+-------+
325 | ``%%`` | A literal ``'%'`` character. | |
326 +-----------+------------------------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328 Notes:
329
330 (1)
331 When used with the :func:`strptime` function, the ``%p`` directive only affects
332 the output hour field if the ``%I`` directive is used to parse the hour.
333
334 (2)
335 The range really is ``0`` to ``61``; this accounts for leap seconds and the
336 (very rare) double leap seconds.
337
338 (3)
339 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
340 calculations when the day of the week and the year are specified.
341
342 Here is an example, a format for dates compatible with that specified in the
343 :rfc:`2822` Internet email standard. [#]_ ::
344
345 >>> from time import gmtime, strftime
346 >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
347 'Thu, 28 Jun 2001 14:17:15 +0000'
348
349 Additional directives may be supported on certain platforms, but only the ones
350 listed here have a meaning standardized by ANSI C.
351
352 On some platforms, an optional field width and precision specification can
353 immediately follow the initial ``'%'`` of a directive in the following order;
354 this is also not portable. The field width is normally 2 except for ``%j`` where
355 it is 3.
356
357
358.. function:: strptime(string[, format])
359
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000360 Parse a string representing a time according to a format. The return value
361 is a :class:`struct_time` as returned by :func:`gmtime` or
362 :func:`localtime`.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364 The *format* parameter uses the same directives as those used by
365 :func:`strftime`; it defaults to ``"%a %b %d %H:%M:%S %Y"`` which matches the
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000366 formatting returned by :func:`ctime`. If *string* cannot be parsed according
367 to *format*, or if it has excess data after parsing, :exc:`ValueError` is
368 raised. The default values used to fill in any missing data when more
369 accurate values cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``.
370 Both *string* and *format* must be strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Christian Heimesfe337bf2008-03-23 21:54:12 +0000372 For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374 >>> import time
Christian Heimesfe337bf2008-03-23 21:54:12 +0000375 >>> time.strptime("30 Nov 00", "%d %b %y") # doctest: +NORMALIZE_WHITESPACE
376 time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
377 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379 Support for the ``%Z`` directive is based on the values contained in ``tzname``
380 and whether ``daylight`` is true. Because of this, it is platform-specific
381 except for recognizing UTC and GMT which are always known (and are considered to
382 be non-daylight savings timezones).
383
384 Only the directives specified in the documentation are supported. Because
385 ``strftime()`` is implemented per platform it can sometimes offer more
386 directives than those listed. But ``strptime()`` is independent of any platform
387 and thus does not necessarily support all directives available that are not
388 documented as supported.
389
390
391.. data:: struct_time
392
393 The type of the time value sequence returned by :func:`gmtime`,
394 :func:`localtime`, and :func:`strptime`.
395
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397.. function:: time()
398
399 Return the time as a floating point number expressed in seconds since the epoch,
400 in UTC. Note that even though the time is always returned as a floating point
401 number, not all systems provide time with a better precision than 1 second.
402 While this function normally returns non-decreasing values, it can return a
403 lower value than a previous call if the system clock has been set back between
404 the two calls.
405
406
407.. data:: timezone
408
409 The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
410 most of Western Europe, positive in the US, zero in the UK).
411
412
413.. data:: tzname
414
415 A tuple of two strings: the first is the name of the local non-DST timezone, the
416 second is the name of the local DST timezone. If no DST timezone is defined,
417 the second string should not be used.
418
419
420.. function:: tzset()
421
422 Resets the time conversion rules used by the library routines. The environment
423 variable :envvar:`TZ` specifies how this is done.
424
Georg Brandl116aa622007-08-15 14:28:22 +0000425 Availability: Unix.
426
427 .. note::
428
429 Although in many cases, changing the :envvar:`TZ` environment variable may
430 affect the output of functions like :func:`localtime` without calling
431 :func:`tzset`, this behavior should not be relied on.
432
433 The :envvar:`TZ` environment variable should contain no whitespace.
434
435 The standard format of the :envvar:`TZ` environment variable is (whitespace
436 added for clarity)::
437
438 std offset [dst [offset [,start[/time], end[/time]]]]
439
440 Where the components are:
441
442 ``std`` and ``dst``
443 Three or more alphanumerics giving the timezone abbreviations. These will be
444 propagated into time.tzname
445
446 ``offset``
447 The offset has the form: ``± hh[:mm[:ss]]``. This indicates the value
448 added the local time to arrive at UTC. If preceded by a '-', the timezone
449 is east of the Prime Meridian; otherwise, it is west. If no offset follows
450 dst, summer time is assumed to be one hour ahead of standard time.
451
452 ``start[/time], end[/time]``
453 Indicates when to change to and back from DST. The format of the
454 start and end dates are one of the following:
455
456 :samp:`J{n}`
457 The Julian day *n* (1 <= *n* <= 365). Leap days are not counted, so in
458 all years February 28 is day 59 and March 1 is day 60.
459
460 :samp:`{n}`
461 The zero-based Julian day (0 <= *n* <= 365). Leap days are counted, and
462 it is possible to refer to February 29.
463
464 :samp:`M{m}.{n}.{d}`
465 The *d*'th day (0 <= *d* <= 6) or week *n* of month *m* of the year (1
466 <= *n* <= 5, 1 <= *m* <= 12, where week 5 means "the last *d* day in
467 month *m*" which may occur in either the fourth or the fifth
468 week). Week 1 is the first week in which the *d*'th day occurs. Day
469 zero is Sunday.
470
471 ``time`` has the same format as ``offset`` except that no leading sign
472 ('-' or '+') is allowed. The default, if time is not given, is 02:00:00.
473
474 ::
475
476 >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
477 >>> time.tzset()
478 >>> time.strftime('%X %x %Z')
479 '02:07:36 05/08/03 EDT'
480 >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
481 >>> time.tzset()
482 >>> time.strftime('%X %x %Z')
483 '16:08:12 05/08/03 AEST'
484
485 On many Unix systems (including \*BSD, Linux, Solaris, and Darwin), it is more
486 convenient to use the system's zoneinfo (:manpage:`tzfile(5)`) database to
487 specify the timezone rules. To do this, set the :envvar:`TZ` environment
488 variable to the path of the required timezone datafile, relative to the root of
489 the systems 'zoneinfo' timezone database, usually located at
490 :file:`/usr/share/zoneinfo`. For example, ``'US/Eastern'``,
491 ``'Australia/Melbourne'``, ``'Egypt'`` or ``'Europe/Amsterdam'``. ::
492
493 >>> os.environ['TZ'] = 'US/Eastern'
494 >>> time.tzset()
495 >>> time.tzname
496 ('EST', 'EDT')
497 >>> os.environ['TZ'] = 'Egypt'
498 >>> time.tzset()
499 >>> time.tzname
500 ('EET', 'EEST')
501
502
503.. seealso::
504
505 Module :mod:`datetime`
506 More object-oriented interface to dates and times.
507
508 Module :mod:`locale`
509 Internationalization services. The locale settings can affect the return values
510 for some of the functions in the :mod:`time` module.
511
512 Module :mod:`calendar`
513 General calendar-related functions. :func:`timegm` is the inverse of
514 :func:`gmtime` from this module.
515
516.. rubric:: Footnotes
517
518.. [#] The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to the
519 preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
520 strict reading of the original 1982 :rfc:`822` standard calls for a two-digit
521 year (%y rather than %Y), but practice moved to 4-digit years long before the
522 year 2000. The 4-digit year has been mandated by :rfc:`2822`, which obsoletes
523 :rfc:`822`.
524