Movatterモバイル変換


[0]ホーム

URL:


Navigation

16.3.time — Time access and conversions

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.

  • Theepoch is the point where the time starts. On January 1st of thatyear, at 0 hours, the “time since the epoch” is zero. For Unix, the epoch is1970. To find out what the epoch is, look atgmtime(0).
  • The functions in this module may not handle dates and times before the epoch orfar in the future. The cut-off point in the future is determined by the Clibrary; for 32-bit systems, it is typically in 2038.
  • Year 2000 (Y2K) issues: Python depends on the platform’s C library, whichgenerally doesn’t have year 2000 issues, since all dates and times arerepresented internally as seconds since the epoch. Functionstrptime()can parse 2-digit years when given%y format code. When 2-digit years areparsed, they are converted according to the POSIX and ISO C standards: values69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.
  • UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, orGMT). The acronym UTC is not a mistake but a compromise between English andFrench.
  • 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:

    FromToUse
    seconds since the epochstruct_time inUTCgmtime()
    seconds since the epochstruct_time inlocal timelocaltime()
    struct_time inUTCseconds since the epochcalendar.timegm()
    struct_time inlocal timeseconds since the epochmktime()

The module defines the following functions and data items:

time.altzone

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.

time.asctime([t])

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.

time.clock()

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.

time.clock_getres(clk_id)

Return the resolution (precision) of the specified clockclk_id.

Availability: Unix.

New in version 3.3.

time.clock_gettime(clk_id)

Return the time of the specified clockclk_id.

Availability: Unix.

New in version 3.3.

time.clock_settime(clk_id,time)

Set the time of the specified clockclk_id.

Availability: Unix.

New in version 3.3.

time.CLOCK_HIGHRES

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.

time.CLOCK_MONOTONIC

Clock that cannot be set and represents monotonic time since some unspecifiedstarting point.

Availability: Unix.

New in version 3.3.

time.CLOCK_MONOTONIC_RAW

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.

time.CLOCK_PROCESS_CPUTIME_ID

High-resolution per-process timer from the CPU.

Availability: Unix.

New in version 3.3.

time.CLOCK_REALTIME

System-wide real-time clock. Setting this clock requires appropriateprivileges.

Availability: Unix.

New in version 3.3.

time.CLOCK_THREAD_CPUTIME_ID

Thread-specific CPU-time clock.

Availability: Unix.

New in version 3.3.

time.ctime([secs])

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().

time.daylight

Nonzero if a DST timezone is defined.

time.get_clock_info(name)

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:

  • adjustable:True if the clock can be changed automatically (e.g. bya NTP daemon) or manually by the system administrator,False otherwise
  • implementation: The name of the underlying C function used to getthe clock value
  • monotonic:True if the clock cannot go backward,False otherwise
  • resolution: The resolution of the clock in seconds (float)

New in version 3.3.

time.gmtime([secs])

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.

time.localtime([secs])

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.

time.mktime(t)

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.

time.monotonic()

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.

time.perf_counter()

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.

time.process_time()

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.

time.sleep(secs)

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.

time.strftime(format[,t])

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:

DirectiveMeaningNotes
%aLocale’s abbreviated weekday name. 
%ALocale’s full weekday name. 
%bLocale’s abbreviated month name. 
%BLocale’s full month name. 
%cLocale’s appropriate date and timerepresentation. 
%dDay of the month as a decimal number [01,31]. 
%HHour (24-hour clock) as a decimal number[00,23]. 
%IHour (12-hour clock) as a decimal number[01,12]. 
%jDay of the year as a decimal number [001,366]. 
%mMonth as a decimal number [01,12]. 
%MMinute as a decimal number [00,59]. 
%pLocale’s equivalent of either AM or PM.(1)
%SSecond as a decimal number [00,61].(2)
%UWeek 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)
%wWeekday as a decimal number [0(Sunday),6]. 
%WWeek 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)
%xLocale’s appropriate date representation. 
%XLocale’s appropriate time representation. 
%yYear without century as a decimal number[00,99]. 
%YYear with century as a decimal number. 
%zTime 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]. 
%ZTime zone name (no characters if no time zoneexists). 
%%A literal'%' character. 

Notes:

  1. When used with thestrptime() function, the%p directive only affectsthe output hour field if the%I directive is used to parse the hour.
  2. The range really is0 to61; value60 is valid intimestamps representing leap seconds and value61 is supportedfor historical reasons.
  3. When used with thestrptime() function,%U and%W are only used incalculations when the day of the week and the year are specified.

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.

time.strptime(string[,format])

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.

classtime.struct_time

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:

IndexAttributeValues
0tm_year(for example, 1993)
1tm_monrange [1, 12]
2tm_mdayrange [1, 31]
3tm_hourrange [0, 23]
4tm_minrange [0, 59]
5tm_secrange [0, 61]; see(2) instrftime() description
6tm_wdayrange [0, 6], Monday is 0
7tm_ydayrange [1, 366]
8tm_isdst0, 1 or -1; see below
N/Atm_zoneabbreviation of timezone name
N/Atm_gmtoffoffset 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.

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 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.

time.timezone

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).

time.tzname

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.

time.tzset()

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:

std anddst
Three or more alphanumerics giving the timezone abbreviations. These will bepropagated into time.tzname
offset
The offset has the form:±hh[:mm[:ss]]. This indicates the valueadded the local time to arrive at UTC. If preceded by a ‘-‘, the timezoneis east of the Prime Meridian; otherwise, it is west. If no offset followsdst, summer time is assumed to be one hour ahead of standard time.
start[/time],end[/time]

Indicates when to change to and back from DST. The format of thestart and end dates are one of the following:

Jn
The Julian dayn (1 <=n <= 365). Leap days are not counted, so inall years February 28 is day 59 and March 1 is day 60.
n
The zero-based Julian day (0 <=n <= 365). Leap days are counted, andit is possible to refer to February 29.
Mm.n.d
Thed‘th day (0 <=d <= 6) or weekn of monthm of the year (1<=n <= 5, 1 <=m <= 12, where week 5 means “the lastd day inmonthm” which may occur in either the fourth or the fifthweek). Week 1 is the first week in which thed‘th day occurs. Dayzero is Sunday.

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

Moduledatetime
More object-oriented interface to dates and times.
Modulelocale
Internationalization services. The locale setting affects the interpretationof many format specifiers instrftime() andstrptime().
Modulecalendar
General calendar-related functions.timegm() is theinverse ofgmtime() from this module.

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.

Previous topic

16.2.io — Core tools for working with streams

Next topic

16.4.argparse — Parser for command-line options, arguments and sub-commands

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp