python帮助手册-----------------time

Python的time模块提供了各种与时间相关的功能,包括时间的访问和转换。尽管这个模块在所有平台上都可用,但并非所有功能都在所有平台上都能使用。时间以自1970年1月1日以来的秒数表示,不考虑闰秒。时间戳在2038年之前在32位系统上可能存在限制。time模块还涉及时间区、夏令时、日期和时间的转换以及与C库的交互。
摘要由CSDN通过智能技术生成

16.3. time — Time access and conversions

                时间——时间的访问和转化 

  This module provides various time-related functions. For related functionality, see also the datetime andcalendar modules.

      这个模块提供了各种与时间相关的功能。有关功能,请参见datatime和calendar模块。

           Although this module is always available, not all functions are available on all platforms.

      虽然这个模块总是可用的,但并不是所有平台都可以使用所有功能

Most of the functions defined in this module call platform C library functions with the same name.

这个模块中定义的大部分功能调用平台C库同名的函数。

It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.

咨询平台文档是有帮助的,因为在平台中这些函数的语义是不同的。

An explanation of some terminology and conventions is in order.一些术语和协议在命令中使用的例子

  • The epoch is the point where the time starts, and is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). To find out what the epoch is on a given platform, look at time.gmtime(0).
  • 纪元是时间的起点,并且依赖于平台。对于Unix,纪元是1970年1月1日0时0分0秒(UTC)。查询已绑定平台的纪元,查看time.gmtime(0)。
  • The term seconds since the epoch refers to the total number of elapsed seconds since the epoch, typically excluding leap seconds. Leap seconds are excluded from this total on all POSIX-compliant platforms.
  • 自纪元以来的秒数是指自纪元以来经过的总秒数,通常不包括闰秒。在所有符合POSIX的平台上,闰秒不包括在总数中。
  • The functions in this module may not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for 32-bit systems, it is typically in 2038.
  • 本模块中的功能可能不会处理纪元之前或遥远的将来的日期和时间。未来的截止点由C库决定;对于32位系统,通常是在2038年。
  • Year 2000 (Y2K) issues: Python depends on the platform’s C library, which generally doesn’t have year 2000 issues, since all dates and times are represented internally as seconds since the epoch. Functionstrptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.
  • 2000年( Y2K )问题: Python依赖于平台的C库,该库通常没有2000年问题,因为所有日期和时间在内部表示为纪元后的秒。当给定% y格式代码时,函数strptime ( )可以解析2位数年份。解析两位数年份时,根据POSIX和ISO C标准进行转换:值69–99映射到1969–1999,值0–68映射到2000–2068。
  • UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or GMT). The acronym UTC is not a mistake but a compromise between English and French.
  • UTC是协调世界时(以前称为格林威治标准时间,或GMT )。缩写UTC不是一个错误,而是英语和法语之间的妥协
  • DST is Daylight Saving Time, an adjustment of the timezone by (usually) one hour during part of the year. DST rules are magic (determined by local law) and can change from year to year. The C library has a table containing the local rules (often it is read from a system file for flexibility) and is the only source of True Wisdom in this respect.

  • DST是夏令时,在一年的部分时间里,时区调整(通常)一小时。DST规则是神奇的(由当地法律决定),并且可以逐年变化。C库有一个包含本地规则的表(为了灵活起见,通常从系统文件中读取),是这方面真正智慧的唯一来源。

  • The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.

  • 各种实时函数的精度可能低于表示其值或参数的单位所建议的精度。例如,在大多数Unix系统上,时钟每秒只“滴答”50或100次

  • On the other hand, the precision of time() and sleep() is better than their Unix equivalents: times are expressed as floating point numbers, time() returns the most accurate time available (using Unixgettimeofday() where available), and sleep() will accept a time with a nonzero fraction (Unix select() is used to implement this, where available).

  • 另一方面,time ( )和sleep ( )的精度优于它们的Unix等价物:时间表示为浮点数,time ( )返回最准确的可用时间(如果可用,使用Unixgettimeofday ( ),sleep ( )将接受非零分数的时间(如果可用,使用Unix select ( )实现)。

  • The time value as returned by gmtime()localtime(), and strptime(), and accepted by asctime(),mktime() and strftime(), is a sequence of 9 integers. The return values of gmtime()localtime(), andstrptime() also offer attribute names for individual fields.

  •  

     

    由gmtime ( )、localtime ( )和strptime ( )返回并被asctime ( )、mktime ( )和strftime ( )接受的时间值是9个整数的序列。gmtime ( )、localtime ( )和trptime ( )的返回值也为各个字段提供属性名称。

     

 

See struct_time for a description of these objects.有关这些对象的描述,请参见struct _ time。

Changed in version 3.3: The struct_time type was extended to provide the tm_gmtoff and tm_zoneattributes when platform supports corresponding struct tm members.

3.3版中发生了变化: struct _ time类型被扩展,以在平台支持相应的struct _ TM成员时提供TM _ gmtoff和TM _ zone属性

Changed in version 3.6: The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.

在3.6版中有所改变:结构时间属性TM _ gmtoff和TM _ zone现在在所有平台上都可用。

  • Use the following functions to convert between time representations:使用以下函数在时间表示之间转换:

    FromToUse
    seconds since the epoch 从纪元开始的几秒钟struct_time in UTCgmtime()
    seconds since the epochstruct_time in local timelocaltime()
    struct_time in UTC 世界协调时的结构时间seconds since the epochcalendar.timegm()
    struct_time in local time 本地时间中的结构时间seconds since the epochmktime()

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

将表示gmtime ( )或localtime ( )返回的时间的元组或struct _ time转换为以下形式的字符串:“孙俊20 23 : 21 : 05 1993”。如果未提供t,则使用localtime ( )返回的当前时间。asctime ( )不使用区域设置信息。

Note  注意

Unlike the C function of the same name, asctime() does not add a trailing newline.

与同名的C函数不同,asctime ( )不添加尾随换行符。

time.clock()

On Unix, return the current processor time as a floating point number expressed in 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.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter()or process_time() instead, depending on your requirements, to have a well defined behaviour.

在Unix上,以以秒为单位的浮点数返回当前处理器时间。“处理器时间”的精确程度,实际上是其含义的定义,取决于同名C函数的精确程度。
在Windows上,此函数基于Win32函数QueryPerformanceCounter ( )以浮点数形式返回自第一次调用此函数以来经过的挂钟秒。分辨率通常优于一微秒。
自3.3版以来就不赞成使用:这个函数的行为取决于平台:根据您的需求,使用perf _ counter ( )或process _ time ( )来定义良好的行为。

time.pthread_getcpuclockid(thread_id)

Return the clk_id of the thread-specific CPU-time clock for the specified thread_id.

返回指定线程id的线程特定CPU时间时钟的clk _ id。

Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value forthread_id.

使用线程化. get _ ident ( )或线程化的ident属性。线程对象以获取线程id的适当值。

Warning       警告

Passing an invalid or expired thread_id may result in undefined behavior, such as segmentation fault.

Availability: Unix (see the man page for pthread_getcpuclockid(3) for further information)

New in version 3.7.

传递无效或过期的thread _ id可能会导致未定义的行为,例如分段错误。
可用性: Unix (有关详细信息,请参见pthread _ getcpuclockid ( 3 )的手册页)
3.7版中的新版本。

time.clock_getres(clk_id)

Return the resolution (precision) of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.

Availability: Unix.

New in version 3.3.

返回指定时钟clk _ id的分辨率(精度)。有关clk _ ID的接受值列表,请参考时钟ID常数。
可用性: Unix。
3.3版中的新版本。

time.clock_gettime(clk_id) → float

Return the time of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values forclk_id.

Availability: Unix.

New in version 3.3.

返回指定时钟clk _ id的时间。有关clk _ ID的接受值列表,请参考时钟ID常数。
可用性: Unix。
3.3版中的新版本。

time.clock_gettime_ns(clk_id) → int

Similar to clock_gettime() but return time as nanoseconds.

Availability: Unix.

New in version 3.7.

类似于clock _ gettime ( ),但返回时间为纳秒。
可用性: Unix。
3.7版中的新版本

time.clock_settime(clk_idtime: float)

Set the time of the specified clock clk_id. Currently, CLOCK_REALTIME is the only accepted value for clk_id.

Availability: Unix.

New in version 3.3.

设置指定时钟clk _ id的时间。目前,时钟实时是clk _ id唯一可接受的值。
可用性: Unix。
3.3版中的新版本。

time.clock_settime_ns(clk_idtime: int)

Similar to clock_settime() but set time with nanoseconds.

Availability: Unix.

New in version 3.7.

类似于clock _ settime ( ),但是用纳秒设置时间。
可用性: Unix。
3.7版中的新版本。

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 toasctime(localtime(secs)). Locale information is not used by ctime().

将从纪元开始以秒为单位表示的时间转换为表示本地时间的字符串。如果未提供secs或无,则使用time ( )返回的当前时间。ctime (秒)相当于asctime (本地时间(秒) )。ctime ( )未使用区域设置信息。

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 value are:

获取指定时钟作为命名空间对象的信息。支持的时钟名称和读取其值的相应函数是:

' clock ' :时间。时钟( )
'单调' :时间。单调( )
“性能计数器”:时间。性能计数器( )
“进程_时间”:时间。进程_时间( )
线程时间:时间。线程时间( )
'时间' :时间。时间( )

The result has the following attributes:        结果具有以下属性:

  • adjustableTrue if the clock can be changed automatically (e.g. by a NTP daemon) or manually by the system administrator, False otherwise
  • 可调:如果时钟可以自动(例如通过NTP守护程序)或由系统管理员手动更改,则为True,否则为False
  • implementation: The name of the underlying C function used to get the clock value. Refer to Clock ID Constants for possible values.
  • 实现:用于获取时钟值的底层C函数的名称。有关可能的值,请参考时钟ID常数。
  • monotonicTrue if the clock cannot go backward, False otherwise
  • 单调:如果时钟不能倒转,则为True,否则为False
  • resolution: The resolution of the clock in seconds (float)
  • 分辨率:时钟的分辨率(秒) (浮点)

New in version 3.3.

3.3版中的新版本。

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.

将纪元后以秒表示的时间转换为UTC中的struct _ time,其中dst标志始终为零。如果未提供secs或无,则使用time ( )返回的当前时间。几分之一秒被忽略。有关struct _ time对象的描述,请参见上文。有关此函数的反函数,请参见calendar . timegm ( )。

time.localtime([secs])

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

像gmtime ( )一样,但是转换为本地时间。如果未提供secs或无,则使用time ( )返回的当前时间。当DST应用于给定时间时,DST标志设置为1。

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

这是localtime ( )的反函数。它的参数是struct _ time或完整的9元组(因为需要dst标志;使用- 1作为dst标志(如果未知),该标志以本地时间表示时间,而不是UTC。它返回一个浮点数,以便与时间兼容( )。如果输入值不能表示为有效时间,则会引发overlowerror或value error (这取决于Python或底层C库是否捕获了无效值)。它可以生成时间的最早日期取决于平台。

time.monotonic() → float

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

返回单调时钟的值(以小数秒为单位),即不能倒回的时钟。时钟不受系统时钟更新的影响。返回值的参考点未定义,因此只有连续调用结果之间的差异有效。

On Windows versions older than Vista, monotonic() detects GetTickCount() integer overflow (32 bits, roll-over after 49.7 days). It increases an internal epoch (reference time) by 232 each time that an overflow is detected. The epoch is stored in the process-local state and so the value of monotonic() may be different in two Python processes running for more than 49 days. On more recent versions of Windows and on other operating systems, monotonic() is system-wide.

在比Vista更早的Windows版本上,单调( )检测到GetTickCount ( )整数溢出( 32位,49.7天后翻转)。每次检测到溢出时,它都会将内部历元(参考时间)增加232。历元存储在进程本地状态中,因此在运行超过49天的两个Python进程中,单调( )的值可能不同。在较新版本的Windows和其他操作系统上,单调( )是全系统的。

New in version 3.3.       3.3版中的新版本。

Changed in version 3.5: The function is now always available.      在3.5版中进行了更改:该功能现在总是可用的。

time.monotonic_ns() → int

Similar to monotonic(), but return time as nanoseconds.

New in version 3.7.

类似于单调( ),但返回时间为纳秒。
3.7版中的新版本。

time.perf_counter() → float

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。它确实包括睡眠期间经过的时间,并且是全系统的。返回值的参考点未定义,因此只有连续调用结果之间的差异有效。
3.3版中的新版本。

time.perf_counter_ns() → int

Similar to perf_counter(), but return time as nanoseconds.

New in version 3.7.

类似于perf _ counter ( ),但返回时间为纳秒。
3.7版中的新版本。

time.process_time() → float

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

返回当前进程的系统和用户CPU时间之和的值(以小数秒为单位)。它不包括睡眠期间经过的时间。根据定义,它是全过程的。返回值的参考点未定义,因此只有连续调用结果之间的差异有效。
3.3版中的新版本。

time.process_time_ns() → int

Similar to process_time() but return time as nanoseconds.

New in version 3.7.

类似于process _ time ( ),但返回时间为纳秒。
3.7版中的新版本。

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. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

暂停调用线程的执行给定的秒数。该参数可以是一个浮点数,表示更精确的睡眠时间。实际暂停时间可能少于请求的时间,因为任何捕捉到的信号都会在执行该信号的捕捉例程后终止睡眠( )。此外,由于系统中其他活动的调度,暂停时间可能比请求的时间长任意数量。

Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).
在3.5版中有所改变:函数现在休眠至少几秒钟,即使休眠被信号中断,除非信号处理程序引发异常(有关原理,请参见PEP 475 )。

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.

The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result:

将表示gmtime ( )或localtime ( )返回的时间的元组或struct _ time转换为格式参数指定的字符串。如果未提供t,则使用localtime ( )返回的当前时间。格式必须是字符串。如果t中的任何字段超出允许的范围,则会引发value error。
0是时间元组中任何位置的合法参数;如果它通常是非法的,则该值被强制为正确的值。
以下指令可以嵌入格式字符串中。它们显示时没有可选的字段宽度和精度规格,并被strftime ( )结果中指示的字符替换:

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 time representation.区域设置的适当日期和时间表示。 
%dDay of the month as a decimal number [01,31].作为十进制数的月份的一天,[ 01,31 ]。 
%HHour (24-hour clock) as a decimal number [00,23].小时( 24小时制)作为十进制数的[ 00,23]。 
%IHour (12-hour clock) as a decimal number [01,12].小时( 12小时制时钟)作为十进制数字[ 01,12 ]。 
%jDay of the year as a decimal number [001,366].作为十进制数的一年中的一天[ 001,366 ]。 
%mMonth as a decimal number [01,12].月作为十进制数[ 01,12 ] 
%MMinute as a decimal number [00,59].作为十进制数的分钟[ 00,59 ]。 
%pLocale’s equivalent of either AM or PM.区域设置相当于上午或下午。(1)
%SSecond as a decimal number [00,61].作为十进制数的第二位[ 00,61 ]。(2)
%UWeek number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.一年中的周数(星期日为一周的第一天),以十进制数[ 00,53表示。第一个星期天之前的新年的所有日子都被认为是第0周。(3)
%w

Weekday as a decimal number [0(Sunday),6].作为十进制数的工作日[ 0 (星期日),6 ]。

作为十进制数的工作日[ 0 (星期日),6 ]。

 
%W

Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.一年中的周数(星期一为一周的第一天),以十进制数[ 00,53表示。新年第一个星期一之前的所有日子都被认为是第0周。

(3)
%xLocale’s appropriate date representation.区域设置的适当日期表示。 
%XLocale’s appropriate time representation.区域设置的适当时间表示。 
%yYear without century as a decimal number [00,99].没有世纪作为十进制数的年份[ 00,99 ]。 
%YYear with century as a decimal number.世纪作为十进制数的年份。 
%z

Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].

时区偏移量,表示与+ HHMM或- HHMM形式的UTC / GMT的正时差或负时差,其中H表示十进制小时数,M表示十进制分钟数[ - 23 : 59,+ 23 : 59 ]。

 
%ZTime zone name (no characters if no time zone exists).时区名称(如果不存在时区,则没有字符)。 
%%A literal '%' character.字面' % '字符。 

Notes:

  1. When used with the strptime() function, the %p directive only affects the output hour field if the %Idirective is used to parse the hour.     当与strptime ( )函数一起使用时,% p指令仅在使用% iditrive解析小时时影响输出小时字段。
  2. The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons.    范围实际上是0到61;值60在代表闰秒的时间戳中有效,值61由于历史原因而被支持。
  3. When used with the strptime() function, %U and %W are only used in calculations when the day of the week and the year are specified.     当与strptime ( )函数一起使用时,只有在指定了星期几和年份时,才会在计算中使用% U和% W。

Here is an example, a format for dates compatible with that specified in the RFC 2822 Internet email standard. [1]

下面是一个例子,日期格式与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'

Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C. To see the full set of format codes supported on your platform, consult thestrftime(3) documentation.

On some platforms, an optional field width and precision specification can immediately follow the initial '%'of a directive in the following order; this is also not portable. The field width is normally 2 except for %j where it is 3.

某些平台上可能支持其他指令,但只有这里列出的指令具有ANSI c标准化的含义。要查看平台上支持的全套格式代码,请参阅《参考时间》( 3 )文档。
在某些平台上,可选的字段宽度和精度规范可以按照以下顺序紧随指令的初始“%”;这也不是便携式的。场宽度通常为2,但% j除外,其中为3。

time.strptime(string[, format])

Parse a string representing a time according to a format. The return value is a struct_time as returned bygmtime() 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 toformat, 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). Bothstring and format must be strings.

根据格式解析表示时间的字符串。返回值是gmtime ( )或localtime ( )返回的struct _ time。
format参数使用与strftime ( )相同的指令;它默认为“% a % b % d % H : % M : % S % Y”,与ctime ( )返回的格式相匹配。如果无法按照格式解析字符串,或者解析后字符串有多余的数据,则会引发value error。当无法推断更准确的值时,用于填充任何缺失数据的默认值为( 1900,1,1,0,0,0,1,- 1 )。字符串和格式都必须是字符串。

For example:

>>>

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

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

Only the directives specified in the documentation are supported. Because strftime() is implemented per platform it can sometimes offer more directives than those listed. But strptime() is independent of any platform and thus does not necessarily support all directives available that are not documented as supported.

对% Z指令的支持基于tzname中包含的值以及日光是否为真。正因为如此,除了识别UTC和GMT之外,它是特定于平台的,这两者总是已知的(并且被认为是非夏令时时区)。
仅支持文档中指定的指令。因为strftime ( )是在每个平台上实现的,所以它有时可以提供比列出的指令更多的指令。但是strptime ( )独立于任何平台,因此不一定支持所有没有记录为支持的指令。

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:

gmtime ( )、localtime ( )和strptime ( )返回的时间值序列的类型。这是一个具有命名元组接口的对象:值可以通过索引和属性名来访问。存在以下值:

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) in strftime()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].

In calls to mktime()tm_isdst may be set to 1 when daylight savings time is in effect, and 0 when it is not. A value of -1 indicates that this is not known, and will usually result in the correct state being filled in.

When a tuple with an incorrect length is passed to a function expecting a struct_time, or having elements of the wrong type, a TypeError is raised.

请注意,与C结构不同,月份值是[ 1,12 ]的范围,而不是[ 0,11 ]。
在对mktime ( )的调用中,当夏令时有效时,TM _ isdst可以设置为1,当夏令时无效时,TM _ isdst可以设置为0。值- 1表示这是未知的,通常会导致填写正确的状态。
当长度不正确的元组被传递给期望struct _ time的函数,或者具有错误类型的元素时,会引发type error。

time.time() → float

Return the time in seconds since the epoch as a floating point number. The specific date of the epoch and the handling of leap seconds is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as Unix time. To find out what the epoch is on a given platform, look atgmtime(0).

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.

The number returned by time() may be converted into a more common time format (i.e. year, month, day, hour, etc…) in UTC by passing it to gmtime() function or in local time by passing it to the localtime()function. In both cases a struct_time object is returned, from which the components of the calendar date may be accessed as attributes.

        以浮点数形式返回从纪元开始的时间(秒)。纪元的具体日期和闰秒的处理取决于平台。在Windows和大多数Unix系统上,纪元是1970年1月1日,00 : 00 : 00 ( UTC ),闰秒不计入纪元后的秒数。这通常称为Unix时间。要了解给定平台上的纪元是什么,请查看gmtime ( 0 )。
       请注意,尽管时间总是以浮点数的形式返回,但并非所有系统都以比1秒更高的精度提供时间。虽然这个函数通常会返回非递减值,但是如果系统时钟在两次调用之间被设置回,它会返回一个低于前一次调用的值。
       通过将时间( )返回的数字传递给gmtime ( )函数,或者通过将它传递给localtime ( )函数,可以在UTC中将其转换为更常见的时间格式(即年、月、日、小时等)。在这两种情况下,都会返回struct _ time对象,日历日期的组件可以作为属性从该对象访问。

time.thread_time() → float

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current thread. It does not include time elapsed during sleep. It is thread-specific by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls in the same thread is valid.

Availability: Windows, Linux, Unix systems supporting CLOCK_THREAD_CPUTIME_ID.

New in version 3.7.

返回当前线程的系统和用户CPU时间之和的值(以小数秒为单位)。它不包括睡眠期间经过的时间。根据定义,它是线程特定的。返回值的参考点未定义,因此只有同一线程中连续调用的结果之间的差异有效。
可用性:支持时钟线程的Windows、Linux、Unix系统。
3.7版中的新版本。

time.thread_time_ns() → int

Similar to thread_time() but return time as nanoseconds.

New in version 3.7.

类似于thread _ time ( ),但返回时间为纳秒。
3.7版中的新版本。

time.time_ns() → int

Similar to time() but returns time as an integer number of nanoseconds since the epoch.

New in version 3.7.

类似于time ( ),但返回的时间为自纪元以来纳秒的整数。
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).

Availability: Unix.

重置库例程使用的时间转换规则。环境变量TZ指定如何做到这一点。它还将设置变量tzname (来自TZ环境变量)、时区( UTC以西的非DST秒)、altzone ( UTC以西的DST秒)和日光(如果这个时区没有夏令时规则,则设置为0;如果夏令时适用于时间、过去、现在或未来,则设置为非零)。
可用性: Unix。

Note

Although in many cases, changing the TZ environment variable may affect the output of functions like localtime() without calling tzset(), this behavior should not be relied on.

The TZ environment variable should contain no whitespace.

注意
虽然在许多情况下,更改TZ环境变量可能会影响localtime ( )等函数的输出,但不需要调用tzset ( ),这种行为不应被依赖。
TZ环境变量不应包含空格。
可用性: Unix。

The standard format of the TZ environment variable is (whitespace added for clarity):

TZ环境变量的标准格式是(为清楚起见添加了空白) :

std offset [dst [offset [,start[/time], end[/time]]]]

Where the components are:其中组件是:

std and dst标准和标准测试

Three or more alphanumerics giving the timezone abbreviations. These will be propagated into time.tzname

给出时区缩写的三个或更多字母数字。这些将被传播到《时代》杂志

offset抵消

The offset has the form: ± hh[:mm[:ss]]. This indicates the value added the local time to arrive at UTC. If preceded by a ‘-‘, the timezone is east of the Prime Meridian; otherwise, it is west. If no offset follows dst, summer time is assumed to be one hour ahead of standard time.
偏移量的形式为: hh [ : mm [ : ss ] ]。这表示到达UTC的本地时间所增加的价值。如果前面有' - ',则时区位于本初子午线以东;否则,它就是西方。如果dst之后没有偏移,则假定夏季时间比标准时间提前一小时。

start[/time], end[/time]

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

指示何时从DST来回切换。开始和结束日期的格式如下:

Jn

The Julian day n (1 <= n <= 365). Leap days are not counted, so in all years February 28 is day 59 and March 1 is day 60.

朱利安日n ( 1 < = n < = 365 )。闰日不计算在内,所以在所有年份中,2月28日是第59天,3月1日是第60天。

n

The zero-based Julian day (0 <= n <= 365). Leap days are counted, and it is possible to refer to February 29.

从零开始的朱利安日( 0 < = n < = 365 )。闰日被计算在内,可以参考2月29日。

Mm.n.d

The d'th day (0 <= d <= 6) of week n of month m of the year (1 <= n <= 5, 1 <= m <= 12, where week 5 means “the last d day in month m” which may occur in either the fourth or the fifth week). Week 1 is the first week in which the d'th day occurs. Day zero is a Sunday.

一年中第m个月的第n周的第d天( 0 < = d < = 6 ) ( 1 < = n < = 5,1 < = m < = 12,其中第5周表示“第m个月的最后d天”,可能出现在第四周或第五周)。第1周是第10天发生的第一周。零日是星期天。

time has the same format as offset except that no leading sign (‘-‘ or ‘+’) is allowed. The default, if time is not given, is 02:00:00.

除了不允许前导符号( ' - '或' + ' )之外,时间与偏移量的格式相同。如果没有给定时间,默认为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 more convenient to use the system’s zoneinfo (tzfile(5)) database to specify the timezone rules. To do this, set the TZ environment variable to the path of the required timezone datafile, relative to the root of the systems ‘zoneinfo’ timezone database, usually located at /usr/share/zoneinfo. For example, 'US/Eastern''Australia/Melbourne','Egypt' or 'Europe/Amsterdam'.

在许多Unix系统(包括* BSD、Linux、Solaris和Darwin )上,使用系统的zoneinfo ( tzfile ( 5 ) )数据库来指定时区规则更方便。为此,将TZ环境变量设置为所需时区数据文件的路径,相对于系统“zoneinfo”时区数据库的根目录,通常位于/ usr / share / zoneinfo。例如,“美国/东方”、“澳大利亚/墨尔本”、“埃及”或“欧洲/阿姆斯特丹”。

>>>

>>> os.environ['TZ'] = 'US/Eastern'
>>> time.tzset()
>>> time.tzname
('EST', 'EDT')
>>> os.environ['TZ'] = 'Egypt'
>>> time.tzset()
>>> time.tzname
('EET', 'EEST')

16.3.2. Clock ID Constants

These constants are used as parameters for clock_getres() and clock_gettime().

这些常数用作clock _ getres ( )和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 usingsettimeofday() or similar.

Availability: Linux 2.6.39 or later.

New in version 3.7.

与CLOCK _ MONOTONIC相同,除了它还包括系统暂停的任何时间。
这允许应用程序获得一个可感知暂停的单调时钟,而不必处理CLOCK _ reality的复杂问题,如果使用settimeofday ( )或类似方法改变时间,这可能会有不连续性。
可用性: Linux 2 . 6 . 39或更高版本。
3.7版中的新版本。

time.CLOCK_HIGHRES

The Solaris OS has a CLOCK_HIGHRES timer that attempts to use an optimal hardware source, and may give close to nanosecond resolution. CLOCK_HIGHRES is the nonadjustable, high-resolution clock.

Availability: Solaris.

New in version 3.3.

Solaris OS有一个CLOCK _ HIGHRES计时器,它试图使用最佳硬件源,并且可以提供接近纳秒的分辨率。CLOCK _ hight是不可调的高分辨率时钟。
可用性: Solaris。
3.3版中的新版本。

time.CLOCK_MONOTONIC

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

Availability: Unix.

New in version 3.3.

无法设置的时钟,表示从某个未指定的起点开始的单调时间。
可用性: Unix。
3.3版中的新版本。

time.CLOCK_MONOTONIC_RAW

Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments.

Availability: Linux 2.6.28 or later.

New in version 3.3.

类似于CLOCK _ MONOTONIC,但提供对不受NTP调整影响的基于硬件的原始时间的访问。
可用性: Linux 2 . 6 . 28或更高版本。
3.3版中的新版本。

time.CLOCK_PROCESS_CPUTIME_ID

High-resolution per-process timer from the CPU.

Availability: Unix.

New in version 3.3.

来自CPU的高分辨率每进程计时器。
可用性: Unix。
3.3版中的新版本。

time.CLOCK_PROF

High-resolution per-process timer from the CPU.

Availability: FreeBSD, NetBSD 7 or later, OpenBSD.

New in version 3.7.

来自CPU的高分辨率每进程计时器。
可用性:免费软件,NetBSD 7或更高版本,OpenBSD。
3.7版中的新版本。

time.CLOCK_THREAD_CPUTIME_ID

Thread-specific CPU-time clock.

Availability: Unix.

New in version 3.3.

线程特定的CPU时间时钟。
可用性: Unix。
3.3版中的新版本。

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

New in version 3.7.

The following constant is the only parameter that can be sent to clock_settime().

绝对值为系统运行和未暂停时间的时间,提供精确的正常运行时间测量,包括绝对时间和间隔时间。
可用性:免费软件,OpenBSD 5.5或更高版本。
3.7版中的新版本。
以下常量是唯一可以发送到clock _ settime ( )的参数。

time.CLOCK_REALTIME

System-wide real-time clock. Setting this clock requires appropriate privileges.

Availability: Unix.

New in version 3.3.

全系统实时时钟。设置此时钟需要适当的权限。
可用性: Unix。
3.3版中的新版本。

16.3.3. Timezone Constants 时区常数

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 if daylight is nonzero. See note below.

本地DST时区的偏移量,以UTC以西秒为单位(如果已定义)。如果本地DST时区位于UTC东部(如西欧,包括英国),则为负。仅在日光非零时使用此选项。见下面的注释。

time.daylight

Nonzero if a DST timezone is defined. See note below.如果定义了DST时区,则非零。见下面的注释。

time.timezone

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK). See note below.

当地(非DST )时区的偏移量,以UTC以西秒为单位(西欧大部分地区为负,美国为正,英国为零)。见下面的注释。

time.tzname

A tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone. If no DST timezone is defined, the second string should not be used. See note below.

两个字符串的元组:第一个是本地非DST时区的名称,第二个是本地DST时区的名称。如果没有定义DST时区,则不应使用第二个字符串。见下面的注释。

Note

 

For the above Timezone constants (altzonedaylighttimezone, 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.

对于上述时区常量( altzone、dalight、tzname ),该值由模块加载时或上次调用tzset ( )时生效的时区规则确定,可能在过去的时间不正确。建议使用localtime ( )中的TM _ gmtoff和TM _ zone结果来获取时区信息。

See also     另见

Module datetime  模块日期时间

More object-oriented interface to dates and times.  更面向对象的日期和时间界面。

Module locale    模块区域设置

Internationalization services. The locale setting affects the interpretation of many format specifiers instrftime() and strptime().

国际化服务。区域设置影响许多格式说明符instrftime ( )和strptime ( )的解释。

Module calendar   日历模块

General calendar-related functions. timegm() is the inverse of gmtime() from this module.

一般日历相关功能。timegm ( )与本模块中的gmtime ( )相反。

Footnotes           注脚

[1]

The use of %Z is now deprecated, but the %z escape that expands to the preferred hour/minute offset is not supported by all ANSI C libraries. Also, a strict reading of the original 1982 RFC 822 standard calls for a two-digit year (%y rather than %Y), but practice moved to 4-digit years long before the year 2000. After that, RFC 822 became obsolete and the 4-digit year has been first recommended by RFC 1123 and then mandated by RFC 2822.

现在不赞成使用% Z,但是并不是所有ANSI C库都支持扩展到首选小时/分钟偏移量的% Z转义。此外,严格阅读原始的1982年RFC 822标准需要两位数的年份( % Y,而不是% Y ),但实际上早在2000年之前,这种做法就已经发展到了4位数的年份。此后,RFC 822变得过时,4位数年份首先由RFC 1123推荐,然后由RFC 2822授权。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值