python的time库

time库是python中处理时间的标准库:

用处:

1.主要用于计算机时间的表达

2.提供获取系统时间并格式化输出功能

3.提供系统级精确计时功能,用于程序性能分析

调用方法:

import time

time.函数名()

time库的三种常用函数

时间获取:time() ctime() gmtime()

时间格式化:strftime() strptime()

程序计时:sleep() perf_counter()

time库的使用

函数

描述

time()

获取当前时间戳(就是计算机内部的计时值)返回的是浮点数>>>time.time()

ctime()

获取当前时间并且以可读的方式表示,返回的是字符串>>>time.ctime()

gmtime()

获取当前计算机可处理的时间格式

>>>time.gmtime()

localtime()

获取计算机本地时间,用法与gmtime相同

时间格式化

将时间以合理地方式展示出来

格式化:类似于字符串格式化,需要有展示模板

展示模板有特定的格式化控制符组成

函数

描述

strftime(tpl,ts)

tp;是格式化模板字符串,用来定义输出效果,而ts是计算机内部的时间类型变量

time.strftime("%Y-%m-%d %H:%M:%S",t)

strptime(str,tpl)

str是字符串形式的时间值

tpl是格式化模板字符串,用来定义输入效果

时间格式化字符串

格式化字符串

日期/时间说明

值的范围

%Y

年份

0000~9999

%m

月份

01~12

%B

月份名称

January~December

%b

月份名称缩写

Jan~Dec

%d

日期

01~31

%A

星期

Monday~Sunday

%a

星期缩写

Mon~Son

%H

小时(24小时)

00~23

%h

小时(12小时)

01~12

%p

上午/下午

AM/PM

%M

分钟

00~60

%S 

秒钟

00~60

程序计时

程序计时应用广泛

程序计时值测量起止动作所经历的事件的过程

测量时间:perf_counter()

产生时间:sleep()

函数

描述

time.perf_counter()

返回一个CPU级别的精准时间计数值,单位为秒,单个值无意义,需要连续调用取差值才有意义

>>>start=time.perf_counter()

>>>end=time.perf_counter()

>>>end-start

time.sleep(s)

s是拟休眠的时间,单位是秒,可以使浮点数

>>>def wait():

       time.sleep(3.3)

>>>wait()

程序将会等待3.3秒后退出

猜你喜欢

转载自blog.csdn.net/qq_39316701/article/details/82634519