This module provides various time-related functions. For relatedfunctionality, see also thedatetime andcalendar modules.
Although this module is always available,not all functions are available on all platforms. Most of the functionsdefined in this module call platform C library functions with the same name. Itmay sometimes be helpful to consult the platform documentation, because thesemantics of these functions varies among platforms.
An explanation of some terminology and conventions is in order.
DST is Daylight Saving Time, an adjustment of the timezone by (usually) onehour during part of the year. DST rules are magic (determined by local law) andcan change from year to year. The C library has a table containing the localrules (often it is read from a system file for flexibility) and is the onlysource of True Wisdom in this respect.
The precision of the various real-time functions may be less than suggested bythe units in which their value or argument is expressed. E.g. on most Unixsystems, the clock “ticks” only 50 or 100 times a second.
On the other hand, the precision oftime() andsleep() is betterthan their Unix equivalents: times are expressed as floating point numbers,time() returns the most accurate time available (using Unixgettimeofday() where available), andsleep() will accept a timewith a nonzero fraction (Unixselect() is used to implement this, whereavailable).
The time value as returned bygmtime(),localtime(), andstrptime(), and accepted byasctime(),mktime() andstrftime(), is a sequence of 9 integers. The return values ofgmtime(),localtime(), andstrptime() also offer attributenames for individual fields.
Seestruct_time for a description of these objects.
Changed in version 3.3:Thestruct_time type was extended to provide thetm_gmtoffandtm_zone attributes when platform supports correspondingstructtm members.
Use the following functions to convert between time representations:
| From | To | Use |
|---|---|---|
| seconds since the epoch | struct_time inUTC | gmtime() |
| seconds since the epoch | struct_time inlocal time | localtime() |
| struct_time inUTC | seconds since the epoch | calendar.timegm() |
| struct_time inlocal time | seconds since the epoch | mktime() |
The module defines the following functions and data items:
The offset of the local DST timezone, in seconds west of UTC, if one is defined.This is negative if the local DST timezone is east of UTC (as in Western Europe,including the UK). Only use this ifdaylight is nonzero.
Convert a tuple orstruct_time representing a time as returned bygmtime() orlocaltime() to a string of the followingform:'SunJun2023:21:051993'. Ift is not provided, the current timeas returned bylocaltime() is used. Locale information is not used byasctime().
Note
Unlike the C function of the same name,asctime() does not add atrailing newline.
On Unix, return the current processor time as a floating point number expressedin 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 anycase, this is the function to use for benchmarking Python or timing algorithms.
On Windows, this function returns wall-clock seconds elapsed since the firstcall to this function, as a floating point number, based on the Win32 functionQueryPerformanceCounter(). The resolution is typically better than onemicrosecond.
Deprecated since version 3.3:The behaviour of this function depends on the platform: useperf_counter() orprocess_time() instead, depending on yourrequirements, to have a well defined behaviour.
Return the resolution (precision) of the specified clockclk_id.
Availability: Unix.
New in version 3.3.
Return the time of the specified clockclk_id.
Availability: Unix.
New in version 3.3.
Set the time of the specified clockclk_id.
Availability: Unix.
New in version 3.3.
The Solaris OS has a CLOCK_HIGHRES timer that attempts to use an optimalhardware source, and may give close to nanosecond resolution. CLOCK_HIGHRESis the nonadjustable, high-resolution clock.
Availability: Solaris.
New in version 3.3.
Clock that cannot be set and represents monotonic time since some unspecifiedstarting point.
Availability: Unix.
New in version 3.3.
Similar toCLOCK_MONOTONIC, but provides access to a rawhardware-based time that is not subject to NTP adjustments.
Availability: Linux 2.6.28 or later.
New in version 3.3.
High-resolution per-process timer from the CPU.
Availability: Unix.
New in version 3.3.
System-wide real-time clock. Setting this clock requires appropriateprivileges.
Availability: Unix.
New in version 3.3.
Thread-specific CPU-time clock.
Availability: Unix.
New in version 3.3.
Convert a time expressed in seconds since the epoch to a string representinglocal time. Ifsecs is not provided orNone, the current time asreturned bytime() is used.ctime(secs) is equivalent toasctime(localtime(secs)). Locale information is not used byctime().
Nonzero if a DST timezone is defined.
Get information on the specified clock as a namespace object.Supported clock names and the corresponding functions to read their valueare:
The result has the following attributes:
New in version 3.3.
Convert a time expressed in seconds since the epoch to astruct_time inUTC in which the dst flag is always zero. Ifsecs is not provided orNone, the current time as returned bytime() is used. Fractionsof a second are ignored. See above for a description of thestruct_time object. Seecalendar.timegm() for the inverse of thisfunction.
Likegmtime() but converts to local time. Ifsecs is not provided orNone, the current time as returned bytime() is used. The dstflag is set to1 when DST applies to the given time.
This is the inverse function oflocaltime(). Its argument is thestruct_time or full 9-tuple (since the dst flag is needed; use-1as the dst flag if it is unknown) which expresses the time inlocal time, notUTC. It returns a floating point number, for compatibility withtime().If the input value cannot be represented as a valid time, eitherOverflowError orValueError will be raised (which depends onwhether 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.
Return the value (in fractional seconds) of a monotonic clock, i.e. a clockthat cannot go backwards. The clock is not affected by system clock updates.The reference point of the returned value is undefined, so that only thedifference between the results of consecutive calls is valid.
On Windows versions older than Vista,monotonic() detectsGetTickCount() integer overflow (32 bits, roll-over after 49.7 days).It increases an internal epoch (reference time) by 232 each timethat an overflow is detected. The epoch is stored in the process-local stateand so the value ofmonotonic() may be different in two Pythonprocesses running for more than 49 days. On more recent versions of Windowsand on other operating systems,monotonic() is system-wide.
Availability: Windows, Mac OS X, Linux, FreeBSD, OpenBSD, Solaris.
New in version 3.3.
Return the value (in fractional seconds) of a performance counter, i.e. aclock with the highest available resolution to measure a short duration. Itdoes include time elapsed during sleep and is system-wide. The referencepoint of the returned value is undefined, so that only the difference betweenthe results of consecutive calls is valid.
New in version 3.3.
Return the value (in fractional seconds) of the sum of the system and userCPU time of the current process. It does not include time elapsed duringsleep. It is process-wide by definition. The reference point of thereturned value is undefined, so that only the difference between the resultsof consecutive calls is valid.
New in version 3.3.
Suspend execution for the given number of seconds. The argument may be afloating point number to indicate a more precise sleep time. The actualsuspension time may be less than that requested because any caught signal willterminate thesleep() following execution of that signal’s catchingroutine. Also, the suspension time may be longer than requested by an arbitraryamount because of the scheduling of other activity in the system.
Convert a tuple orstruct_time representing a time as returned bygmtime() orlocaltime() to a string as specified by theformatargument. Ift is not provided, the current time as returned bylocaltime() is used.format must be a string.ValueError israised if any field int is outside of the allowed range.
0 is a legal argument for any position in the time tuple; if it is normallyillegal the value is forced to a correct one.
The following directives can be embedded in theformat string. They are shownwithout the optional field width and precision specification, and are replacedby the indicated characters in thestrftime() result:
| Directive | Meaning | Notes |
|---|---|---|
| %a | Locale’s abbreviated weekday name. | |
| %A | Locale’s full weekday name. | |
| %b | Locale’s abbreviated month name. | |
| %B | Locale’s full month name. | |
| %c | Locale’s appropriate date and timerepresentation. | |
| %d | Day of the month as a decimal number [01,31]. | |
| %H | Hour (24-hour clock) as a decimal number[00,23]. | |
| %I | Hour (12-hour clock) as a decimal number[01,12]. | |
| %j | Day of the year as a decimal number [001,366]. | |
| %m | Month as a decimal number [01,12]. | |
| %M | Minute as a decimal number [00,59]. | |
| %p | Locale’s equivalent of either AM or PM. | (1) |
| %S | Second as a decimal number [00,61]. | (2) |
| %U | Week number of the year (Sunday as the firstday of the week) as a decimal number [00,53].All days in a new year preceding the firstSunday are considered to be in week 0. | (3) |
| %w | Weekday as a decimal number [0(Sunday),6]. | |
| %W | Week number of the year (Monday as the firstday of the week) as a decimal number [00,53].All days in a new year preceding the firstMonday are considered to be in week 0. | (3) |
| %x | Locale’s appropriate date representation. | |
| %X | Locale’s appropriate time representation. | |
| %y | Year without century as a decimal number[00,99]. | |
| %Y | Year with century as a decimal number. | |
| %z | Time zone offset indicating a positive ornegative time difference from UTC/GMT of theform +HHMM or -HHMM, where H represents decimalhour digits and M represents decimal minutedigits [-23:59, +23:59]. | |
| %Z | Time zone name (no characters if no time zoneexists). | |
| %% | A literal'%' character. |
Notes:
Here is an example, a format for dates compatible with that specified in theRFC 2822 Internet email standard.[1]
>>>fromtimeimportgmtime,strftime>>>strftime("%a, %d %b %Y %H:%M:%S +0000",gmtime())'Thu, 28 Jun 2001 14:17:15 +0000'
Additional directives may be supported on certain platforms, but only theones listed here have a meaning standardized by ANSI C. To see the full setof format codes supported on your platform, consult thestrftime(3)documentation.
On some platforms, an optional field width and precision specification canimmediately follow the initial'%' of a directive in the following order;this is also not portable. The field width is normally 2 except for%j whereit is 3.
Parse a string representing a time according to a format. The return valueis astruct_time as returned bygmtime() orlocaltime().
Theformat parameter uses the same directives as those used bystrftime(); it defaults to"%a%b%d%H:%M:%S%Y" which matches theformatting returned byctime(). Ifstring cannot be parsed accordingtoformat, or if it has excess data after parsing,ValueError israised. The default values used to fill in any missing data when moreaccurate values cannot be inferred are(1900,1,1,0,0,0,0,1,-1).Bothstring andformat must be strings.
For example:
>>>importtime>>>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)
Support for the%Z directive is based on the values contained intznameand whetherdaylight is true. Because of this, it is platform-specificexcept for recognizing UTC and GMT which are always known (and are considered tobe non-daylight savings timezones).
Only the directives specified in the documentation are supported. Becausestrftime() is implemented per platform it can sometimes offer moredirectives than those listed. Butstrptime() is independent of any platformand thus does not necessarily support all directives available that are notdocumented as supported.
The type of the time value sequence returned bygmtime(),localtime(), andstrptime(). It is an object with anamedtuple interface: values can be accessed by index and by attribute name. Thefollowing values are present:
Index Attribute Values 0 tm_year (for example, 1993) 1 tm_mon range [1, 12] 2 tm_mday range [1, 31] 3 tm_hour range [0, 23] 4 tm_min range [0, 59] 5 tm_sec range [0, 61]; see(2) instrftime() description 6 tm_wday range [0, 6], Monday is 0 7 tm_yday range [1, 366] 8 tm_isdst 0, 1 or -1; see below N/A tm_zone abbreviation of timezone name N/A tm_gmtoff offset east of UTC in seconds Note that unlike the C structure, the month value is a range of [1, 12], not[0, 11]. A-1 argument as the daylightsavings flag, passed tomktime() will usually result in the correctdaylight savings state to be filled in.
When a tuple with an incorrect length is passed to a function expecting astruct_time, or having elements of the wrong type, aTypeError is raised.
Changed in version 3.3:tm_gmtoff andtm_zone attributes are available on platformswith C library supporting the corresponding fields instructtm.
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 pointnumber, not all systems provide time with a better precision than 1 second.While this function normally returns non-decreasing values, it can return alower value than a previous call if the system clock has been set back betweenthe two calls.
The offset of the local (non-DST) timezone, in seconds west of UTC (negative inmost of Western Europe, positive in the US, zero in the UK).
A tuple of two strings: the first is the name of the local non-DST timezone, thesecond is the name of the local DST timezone. If no DST timezone is defined,the second string should not be used.
Resets the time conversion rules used by the library routines. The environmentvariableTZ specifies how this is done.
Availability: Unix.
Note
Although in many cases, changing theTZ environment variable mayaffect the output of functions likelocaltime() without callingtzset(), this behavior should not be relied on.
TheTZ environment variable should contain no whitespace.
The standard format of theTZ environment variable is (whitespaceadded for clarity):
stdoffset[dst[offset[,start[/time],end[/time]]]]
Where the components are:
Indicates when to change to and back from DST. The format of thestart and end dates are one of the following:
time has the same format asoffset except that no leading sign(‘-‘ or ‘+’) is allowed. The default, if time is not given, is 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'
On many Unix systems (including *BSD, Linux, Solaris, and Darwin), it is moreconvenient to use the system’s zoneinfo (tzfile(5)) database tospecify the timezone rules. To do this, set theTZ environmentvariable to the path of the required timezone datafile, relative to the root ofthe systems ‘zoneinfo’ timezone database, usually located at/usr/share/zoneinfo. For example,'US/Eastern','Australia/Melbourne','Egypt' or'Europe/Amsterdam'.
>>>os.environ['TZ']='US/Eastern'>>>time.tzset()>>>time.tzname('EST', 'EDT')>>>os.environ['TZ']='Egypt'>>>time.tzset()>>>time.tzname('EET', 'EEST')
See also
Footnotes
| [1] | The use of%Z is now deprecated, but the%z escape that expands to thepreferred hour/minute offset is not supported by all ANSI C libraries. Also, astrict reading of the original 1982RFC 822 standard calls for a two-digityear (%y rather than %Y), but practice moved to 4-digit years long before theyear 2000. After that,RFC 822 became obsolete and the 4-digit year hasbeen first recommended byRFC 1123 and then mandated byRFC 2822. |
16.2.io — Core tools for working with streams
16.4.argparse — Parser for command-line options, arguments and sub-commands
Enter search terms or a module, class or function name.