更多详细time库函数参考 https://docs.python.org/3/library/time.html?highlight=strftime#time
形式:
import time
time.() #下面即将介绍各种()函数
一、时间获取:
1.time():获取当前计算机内部时间,返回浮点数
>>> time.time()
1524146321.7763612 #看不懂的时间表示。。。
2.ctime():以易读方式获得当前时间,返回字符串
>>> time.ctime()
'Thu Apr 19 21:59:34 2018' #星期四 2018-4-19 21:59:34
3.gmtime():获取当前时间,返回计算机可处理的时间格式, 以UTC的时间计
>>> time.gmtime()
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=19, tm_hour=14, tm_min=1, tm_sec=8, tm_wday=3, tm_yday=109, tm_isdst=0) #不知为什么,这个时间有误。。。
4.localtime():获取计算机当前时间,以当地时间计
>>> time.localtime()
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=20, tm_hour=10, tm_min=12, tm_sec=38, tm_wday=4, tm_yday=110, tm_isdst=0)
二、时间格式化:
1.strftime(tpl,ts):tpl是格式化模板字符串,用来定义输出效果,ts是时间变量
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 time representation. | |
%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 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. | (3) |
%w |
Weekday as a decimal number [0(Sunday),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. | (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 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]. | |
%Z |
Time zone name (no characters if no time zone exists). | |
%% |
A literal '%' character. |
>>> time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
'2018-04-20 10:34:57'
2.strptime(str,tpl):str是字符串形式的时间值,tpl是格式化模板字符串,定义输出效果
>>> time.strptime('2018-4-19 22:14:15','%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=19, tm_hour=22, tm_min=14, tm_sec=15, tm_wday=3, tm_yday=109, tm_isdst=-1)
三、程序计时:
1.sleep(s):休眠时间,以秒为单位,可以是浮点数,即等待s秒
2.perf_counter():返回一个CPU级别的精确时间计数,单位为秒,通过连续求差值可获得程序执行时间
>>> start=time.perf_counter()
>>> end=time.perf_counter()
>>> end-start
10.702251718395534