A weekly Python standard library | time

Technology blog: https: //github.com/yongxinz/tech-blog

At the same time, I also welcome the attention of the public micro-channel number AlwaysBeta , more exciting content to wait for you.

Almost all of the official code, we need to deal with time. In Python, the processing time associated with the module comprises time, datetimeas well calendar, This section explains time module.

In Python, the time expressed in three ways, namely, a time stamp, time strings formatted and structured time

  1. Timestamp ( timestamp): that is, after January 1, 1970 seconds, for example 1506388236.216345, can time.time()be obtained. Timestamp is a floating-point number, you can add and subtract, but please be careful not to let the results exceeded the value range.
  2. Formatted time string ( string_time): this is every minute of our common time string date when, for example 2017-09-26 09:12:48, can time.strftime('%Y-%m-%d')be obtained;
  3. Structured Time ( struct_time): a polyol containing the hour, minute tuples date when, for example time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=9, tm_min=14, tm_sec=50, tm_wday=1, tm_yday=269, tm_isdst=0), can time.localtime()be obtained.

Due to the time Python module to achieve the main C library calls, so each platform may vary. time module currently supports only to 2038 years ago. If you need treatment outside the scope of the date, use the datetime module.

UTC (Coordinated Universal Time, UTC), ie Greenwich astronomical time, the world standard time. Our China East eight districts, earlier than UTC 8 hours, which is UTC + 8. About abbreviation UTC, there is a story, you may have noticed, according to the English acronym, should be CUT, rather than UTC. But the world abbreviated in French when coordination TUC, the two countries not to each other, as a compromise, and finally simply referred to as UTC.

The DST (Daylight Saving Time) i.e. daylight saving time.

Structured Time struct_time( )

Using time.localtime()other methods to obtain a structured time tuples.

>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=10, tm_min=6, tm_sec=49, tm_wday=1, tm_yday=269, tm_isdst=0)

Structured time tuple total of nine elements, arranged in order in the following table:

index Attributes Ranges
0 tm_year (years) For example, 2017
1 tm_mon (Mon) 1 - 12
2 tm_mday (Japan) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min (points) 0 - 59
5 tm_sec (s) 0 - 61
6 tm_wday(weekday) 0--6 (0 for Monday)
7 tm_yday (the first day of the year) 1 - 366
8 tm_isdst (whether it is daylight saving time) The default is -1

Since the structure of time is a tuple, then it can be indexed by values, may be fragmented, or by obtaining a value corresponding to the attribute name.

>>>import time
>>> lt = time.localtime()
>>> lt
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=9, tm_min=27, tm_sec=29, tm_wday=1, tm_yday=269, tm_isdst=0)
>>> lt[3]
9
>>> lt[2:5]
(26, 9, 27)
>>> lt.tm_wday
1

But remember, Python type of time is an immutable type, all time values are read-only and can not be changed ! !

>>> lt.tm_wday = 2
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    lt.tm_wday = 2
AttributeError: readonly attribute

Time Format String

Using time.strftime('%Y-%m-%d %H:%M:%S')other methods to obtain a time string format.

>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2017-09-26 10:04:28'

Note that one of the spaces, dashes and the modified appearance are colon symbol, control action is that really percent sign. For formatting control string "%Y-%m-%d %H:%M:%Smeaning in the following table, wherein each letter represents shown, note the difference sensitive:

format meaning
%a Local week shorthand name (eg Thursday to Thu)
%A The name of the local week full name (such as Thursday to Thursday)
%b Local month names are abbreviated (eg August to agu)
%B Local month names the full name (eg August to august)
%c Local string corresponding date and time representation (eg: 15/08/27 10:20:06)
%d The first few days of the month (01--31)
%f Microsecond (0.999999 range)
%H The first few hours (24-hour format, 00--23) of the day
%I The first few hours (12 hour 0 - 11)
%j The first day of the year (001--366)
%m Month (01--12)
%M The number of minutes (00--59)
%p Am or pm local identifier
%S Sec (00--61)
% U Weeks of the year. (00--53 Sunday is the beginning of a week.) All days prior to the first Sunday in Week 0.
%w The first few days of the week (0 - 6,0 Sunday)
%W % U and basically the same, except that% W with a week beginning Monday.
%x Local string corresponding date (e.g., 15/08/01)
%X String corresponding local time (e.g., 08:08:10)
%Y Two numbers indicate the year - remove Century Year (9900)
%Y Full year (four digits indicate the year)
%from UTC time interval (if the local time, an empty string)
%FROM Time zone name (if local time, returns an empty string)
%% '%'character

time module main method

time.sleep(t)

One of the most common methods time module, or to pause the program sleep t seconds, t may be an integer or floating point.

time.time()

Returns the current system time stamp. Timestamps can do arithmetic.

>>> time.time()
1506391907.020303

This method is often used to calculate the running time:

import time

def func():
    time.sleep(1.14)
    pass

t1 = time.time()
func()
t2 = time.time()
print(t2 - t1)

time.gmtime([secs])

The time stamp is converted to a structured time zone UTC. The default value of the optional parameter secs time.time().

>>> time.gmtime()
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=2, tm_min=14, tm_sec=17, tm_wday=1, tm_yday=269, tm_isdst=0)

>>> t = time.time() - 10000
>>> time.gmtime(t)
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=25, tm_hour=23, tm_min=31, tm_sec=3, tm_wday=0, tm_yday=268, tm_isdst=0)

time.localtime([secs])

The structure of a time stamp is converted to the current time zone. If the parameter is not provided secs, places subject to the current time, that is time.time().

>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=10, tm_min=20, tm_sec=42, tm_wday=1, tm_yday=269, tm_isdst=0)

>>> time.localtime(1406391907)
time.struct_time(tm_year=2014, tm_mon=7, tm_mday=27, tm_hour=0, tm_min=25, tm_sec=7, tm_wday=6, tm_yday=208, tm_isdst=0)

>>> time.localtime(time.time() + 10000)
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=13, tm_min=7, tm_sec=54, tm_wday=1, tm_yday=269, tm_isdst=0)

time.ctime([secs])

The format string into a timestamp of the local time. The default use time.time()as a parameter.

>>> time.ctime()
'Tue Sep 26 10:22:31 2017'
>>> time.ctime(time.time())
'Tue Sep 26 10:23:51 2017'
>>> time.ctime(1406391907)
'Sun Jul 27 00:25:07 2014'
>>> time.ctime(time.time() + 10000)
'Tue Sep 26 13:11:55 2017'

time.asctime([t])

把一个结构化时间转换为Sun Aug 23 14:31:59 2017这种形式的格式化时间字符串。默认将time.localtime()作为参数。

>>> time.asctime()
'Tue Sep 26 10:27:23 2017'

>>> time.asctime(time.time())
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    time.asctime(time.time())
TypeError: Tuple or struct_time argument required
    
>>> time.asctime(time.localtime())
'Tue Sep 26 10:27:45 2017'
>>> time.asctime(time.gmtime())
'Tue Sep 26 02:27:57 2017'

time.mktime(t)

将一个结构化时间转化为时间戳。time.mktime()执行与gmtime(),localtime()相反的操作,它接收struct_time对象作为参数,返回用秒数表示时间的浮点数。如果输入的值不是一个合法的时间,将触发OverflowErrorValueError

>>> time.mktime(1406391907)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    time.mktime(1406391907)
TypeError: Tuple or struct_time argument required
    
>>> time.mktime(time.localtime())
1506393039.0

time.strftime(format [, t])

返回格式化字符串表示的当地时间。把一个struct_time(如time.localtime()time.gmtime()的返回值)转化为格式化的时间字符串,显示的格式由参数format决定。如果未指定 t,默认传入time.localtime()。如果元组中任何一个元素越界,就会抛出ValueError的异常。

>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2017-09-26 10:34:50'
>>> time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())
'2017-09-26 02:34:53'

time.strptime(string[,format])

将格式化时间字符串转化成结构化时间。该方法是time.strftime()方法的逆操作。time.strptime()方法根据指定的格式把一个时间字符串解析为时间元组。要注意的是,你提供的字符串要和 format 参数的格式一一对应,如果 string 中日期间使用“-”分隔,format 中也必须使用“-”分隔,时间中使用冒号“:”分隔,后面也必须使用冒号分隔,否则会报格式不匹配的错误。并且值也要在合法的区间范围内,千万不要整出 14 个月来。

>>> import time
>>> stime = "2017-09-26 12:11:30"
>>> st = time.strptime(stime,"%Y-%m-%d %H:%M:%S")
>>> st
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=12, tm_min=11, tm_sec=30, tm_wday=1, tm_yday=269, tm_isdst=-1)
>>> for item in st:
    print(item)


2017
9
26
12
11
30
1
269
-1
>>> wrong_time = "2017-14-26 12:11:30"
>>> st  = time.strptime(wrong_time,"%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    st  = time.strptime(wrong_time,"%Y-%m-%d %H:%M:%S")
  File "C:\Python36\lib\_strptime.py", line 559, in _strptime_time
    tt = _strptime(data_string, format)[0]
  File "C:\Python36\lib\_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data '2017-14-26 12:11:30' does not match format '%Y-%m-%d %H:%M:%S'

time.clock()

返回执行当前程序的 CPU 时间。用来衡量不同程序的耗时。该方法在不同的系统上含义不同。在 Unix 系统上,它返回的是“进程时间”,用秒表示的浮点数(时间戳)。在 Windows 中,第一次调用,返回的是进程运行的实际时间,而第二次之后的调用是自第一次调用以后到现在的运行时间。

import time

def procedure() :
  time.sleep(3)

time1 = time.clock()
procedure()
print(time.clock() - time1, "seconds process time!") 

# 2.999257758349577 seconds process time!

时间格式之间的转换

Python 的三种类型时间格式,可以互相进行转换,如下图和下表所示:

image.png-23.5kB

方法
时间戳 UTC结构化时间 gmtime()
时间戳 本地结构化时间 localtime()
UTC结构化时间 时间戳 calendar.timegm()
本地结构化时间 时间戳 mktime()
结构化时间 格式化字符串 strftime()
格式化字符串 结构化时间 strptime()
>>> t = time.time()         # t是一个时间戳

>>> time.gmtime(t - 10000)      # t减去1万秒,然后转换成UTC结构化时间
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=25, tm_hour=22, tm_min=50, tm_sec=36, tm_wday=0, tm_yday=268, tm_isdst=0)

>>> lt = time.localtime(t - 10000)  # t减去1万秒,然后转换成中国本地结构化时间
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=6, tm_min=50, tm_sec=36, tm_wday=1, tm_yday=269, tm_isdst=0)

>>> time.mktime(lt)     # 从本地结构化时间转换为时间戳
1506379836.0
>>> st = time.strftime("%Y-%m-%d %H:%M:%S",lt)  # 从本地结构化时间转换为时间字符串
>>> st
'2017-09-26 06:50:36'

>>> lt2 = time.strptime(st, "%Y-%m-%d %H:%M:%S") # 从时间字符串转换为结构化时间
>>> lt2
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=6, tm_min=50, tm_sec=36, tm_wday=1, tm_yday=269, tm_isdst=-1)

相关文档:

https://pymotw.com/3/time/index.html

http://www.liujiangblog.com/course/python/68

发布了28 篇原创文章 · 获赞 30 · 访问量 4万+

Guess you like

Origin blog.csdn.net/zyx6a/article/details/104064265