Python-基础(6.2)-time

time模块— Time access and conversions

Jupter notebook NBViewer传送门
This module provides various time-related functions.

Functions

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'. If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime().

1
2
3
4
5
import time
import datetime
print(time.asctime())

print(time.asctime(datetime.datetime.now().timetuple()))
Wed Apr 24 15:34:33 2019
Wed Apr 24 15:34:33 2019

time.ctime([secs])

Convert a time expressed in seconds since the epoch to a string representing local time.
If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

1
time.ctime(datetime.datetime.now().timestamp())
'Wed Apr 24 15:36:47 2019'

time.gmtime([secs])

Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. Fractions of a second are ignored. See above for a description of the struct_time object. See calendar.timegm() for the inverse of this function.

1
time.gmtime(datetime.datetime.now().timestamp())
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=24, tm_hour=7, tm_min=39, tm_sec=19, tm_wday=2, tm_yday=114, tm_isdst=0)

time.localtime([secs])

Like gmtime() but converts to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.

1
time.localtime(datetime.datetime.now().timestamp())
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=24, tm_hour=15, tm_min=40, tm_sec=7, tm_wday=2, tm_yday=114, tm_isdst=0)

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.

1
time.mktime(datetime.datetime.now().timetuple())
1556091812.0

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.

0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one.

1
time.strftime('%Y-%m-%d,%a %H:%M:%S', time.gmtime())
'2019-04-24,Wed 07:47:44'

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). Both string and format must be strings.

1
time.strptime('2019-04-24,Wed 07:47:44','%Y-%m-%d,%a %H:%M:%S')
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=24, tm_hour=7, tm_min=47, tm_sec=44, tm_wday=2, tm_yday=114, tm_isdst=-1)

Classes in time module

class time.struct_time

The type of the time value sequence returned by gmtime(), localtime(), and strptime().

It is an object with a named tuple interface: values can be accessed by index and by attribute name.

The following values are present:

1
2
3
4
5
6
7
8
9
10
11
12
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) in strftime() 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

1
2
import time
help(time)
Help on built-in module time:

NAME
    time - This module provides various functions to manipulate time values.

DESCRIPTION
    There are two standard representations of time.  One is the number
    of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
    or a floating point number (to represent fractions of seconds).
    The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
    The actual value can be retrieved by calling gmtime(0).

    The other representation is a tuple of 9 integers giving local time.
    The tuple items are:
      year (including century, e.g. 1998)
      month (1-12)
      day (1-31)
      hours (0-23)
      minutes (0-59)
      seconds (0-59)
      weekday (0-6, Monday is 0)
      Julian day (day in the year, 1-366)
      DST (Daylight Savings Time) flag (-1, 0 or 1)
    If the DST flag is 0, the time is given in the regular time zone;
    if it is 1, the time is given in the DST time zone;
    if it is -1, mktime() should guess based on the date and time.

CLASSES
    builtins.tuple(builtins.object)
        struct_time

    class struct_time(builtins.tuple)
     |  struct_time(iterable=(), /)
     |  
     |  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.
     |  
     |  Note that several fields' values are not the same as those defined by
     |  the C language standard for struct tm.  For example, the value of the
     |  field tm_year is the actual year, not year - 1900.  See individual
     |  fields' descriptions for details.
     |  
     |  Method resolution order:
     |      struct_time
     |      builtins.tuple
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __reduce__(...)
     |      Helper for pickle.
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  tm_gmtoff
     |      offset from UTC in seconds
     |  
     |  tm_hour
     |      hours, range [0, 23]
     |  
     |  tm_isdst
     |      1 if summer time is in effect, 0 if not, and -1 if unknown
     |  
     |  tm_mday
     |      day of month, range [1, 31]
     |  
     |  tm_min
     |      minutes, range [0, 59]
     |  
     |  tm_mon
     |      month of year, range [1, 12]
     |  
     |  tm_sec
     |      seconds, range [0, 61])
     |  
     |  tm_wday
     |      day of week, range [0, 6], Monday is 0
     |  
     |  tm_yday
     |      day of year, range [1, 366]
     |  
     |  tm_year
     |      year, for example, 1993
     |  
     |  tm_zone
     |      abbreviation of timezone name
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  n_fields = 11
     |  
     |  n_sequence_fields = 9
     |  
     |  n_unnamed_fields = 0
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.tuple:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __getitem__(self, key, /)
     |      Return self[key].
     |  
     |  __getnewargs__(self, /)
     |  
     |  __gt__(self, value, /)
     |      Return self>value.
     |  
     |  __hash__(self, /)
     |      Return hash(self).
     |  
     |  __iter__(self, /)
     |      Implement iter(self).
     |  
     |  __le__(self, value, /)
     |      Return self<=value.
     |  
     |  __len__(self, /)
     |      Return len(self).
     |  
     |  __lt__(self, value, /)
     |      Return self<value.
     |  
     |  __mul__(self, value, /)
     |      Return self*value.
     |  
     |  __ne__(self, value, /)
     |      Return self!=value.
     |  
     |  __rmul__(self, value, /)
     |      Return value*self.
     |  
     |  count(self, value, /)
     |      Return number of occurrences of value.
     |  
     |  index(self, value, start=0, stop=9223372036854775807, /)
     |      Return first index of value.
     |      
     |      Raises ValueError if the value is not present.

FUNCTIONS
    asctime(...)
        asctime([tuple]) -> string

        Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
        When the time tuple is not present, current time as returned by localtime()
        is used.

    clock(...)
        clock() -> floating point number

        Return the CPU time or real time since the start of the process or since
        the first call to clock().  This has as much precision as the system
        records.

    clock_getres(...)
        clock_getres(clk_id) -> floating point number

        Return the resolution (precision) of the specified clock clk_id.

    clock_gettime(...)
        clock_gettime(clk_id) -> float

        Return the time of the specified clock clk_id.

    clock_gettime_ns(...)
        clock_gettime_ns(clk_id) -> int

        Return the time of the specified clock clk_id as nanoseconds.

    clock_settime(...)
        clock_settime(clk_id, time)

        Set the time of the specified clock clk_id.

    clock_settime_ns(...)
        clock_settime_ns(clk_id, time)

        Set the time of the specified clock clk_id with nanoseconds.

    ctime(...)
        ctime(seconds) -> string

        Convert a time in seconds since the Epoch to a string in local time.
        This is equivalent to asctime(localtime(seconds)). When the time tuple is
        not present, current time as returned by localtime() is used.

    get_clock_info(...)
        get_clock_info(name: str) -> dict

        Get information of the specified clock.

    gmtime(...)
        gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
                               tm_sec, tm_wday, tm_yday, tm_isdst)

        Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
        GMT).  When 'seconds' is not passed in, convert the current time instead.

        If the platform supports the tm_gmtoff and tm_zone, they are available as
        attributes only.

    localtime(...)
        localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                                  tm_sec,tm_wday,tm_yday,tm_isdst)

        Convert seconds since the Epoch to a time tuple expressing local time.
        When 'seconds' is not passed in, convert the current time instead.

    mktime(...)
        mktime(tuple) -> floating point number

        Convert a time tuple in local time to seconds since the Epoch.
        Note that mktime(gmtime(0)) will not generally return zero for most
        time zones; instead the returned value will either be equal to that
        of the timezone or altzone attributes on the time module.

    monotonic(...)
        monotonic() -> float

        Monotonic clock, cannot go backward.

    monotonic_ns(...)
        monotonic_ns() -> int

        Monotonic clock, cannot go backward, as nanoseconds.

    perf_counter(...)
        perf_counter() -> float

        Performance counter for benchmarking.

    perf_counter_ns(...)
        perf_counter_ns() -> int

        Performance counter for benchmarking as nanoseconds.

    process_time(...)
        process_time() -> float

        Process time for profiling: sum of the kernel and user-space CPU time.

    process_time_ns(...)
        process_time() -> int

        Process time for profiling as nanoseconds:
        sum of the kernel and user-space CPU time.

    pthread_getcpuclockid(...)
        pthread_getcpuclockid(thread_id) -> int

        Return the clk_id of a thread's CPU time clock.

    sleep(...)
        sleep(seconds)

        Delay execution for a given number of seconds.  The argument may be
        a floating point number for subsecond precision.

    strftime(...)
        strftime(format[, tuple]) -> string

        Convert a time tuple to a string according to a format specification.
        See the library reference manual for formatting codes. When the time tuple
        is not present, current time as returned by localtime() is used.

        Commonly used format codes:

        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %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 time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.

        Other codes may be available on your platform.  See documentation for
        the C library strftime function.

    strptime(...)
        strptime(string, format) -> struct_time

        Parse a string to a time tuple according to a format specification.
        See the library reference manual for formatting codes (same as
        strftime()).

        Commonly used format codes:

        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %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 time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.

        Other codes may be available on your platform.  See documentation for
        the C library strftime function.

    thread_time(...)
        thread_time() -> float

        Thread time for profiling: sum of the kernel and user-space CPU time.

    thread_time_ns(...)
        thread_time() -> int

        Thread time for profiling as nanoseconds:
        sum of the kernel and user-space CPU time.

    time(...)
        time() -> floating point number

        Return the current time in seconds since the Epoch.
        Fractions of a second may be present if the system clock provides them.

    time_ns(...)
        time_ns() -> int

        Return the current time in nanoseconds since the Epoch.

    tzset(...)
        tzset()

        Initialize, or reinitialize, the local timezone to the value stored in
        os.environ['TZ']. The TZ environment variable should be specified in
        standard Unix timezone format as documented in the tzset man page
        (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently
        fall back to UTC. If the TZ environment variable is not set, the local
        timezone is set to the systems best guess of wallclock time.
        Changing the TZ environment variable without calling tzset *may* change
        the local timezone used by methods such as localtime, but this behaviour
        should not be relied on.

DATA
    CLOCK_MONOTONIC = 1
    CLOCK_MONOTONIC_RAW = 4
    CLOCK_PROCESS_CPUTIME_ID = 2
    CLOCK_REALTIME = 0
    CLOCK_THREAD_CPUTIME_ID = 3
    altzone = -28800
    daylight = 0
    timezone = -28800
    tzname = ('CST', 'CST')

FILE
    (built-in)