python基础 — time库
时间获取------- time.time() 、time.ctime() 、time.gmtime()
时间格式化-------strftime() 、 strptime()
程序计时-------sleep() 、perf_counter()
时间获取函数
time()-------获取当前时间戳,浮点数形式
1 print(time.time())
2 # 输出: 1575428957.5652914
ctime()-------以可读的方式返回字符串时间
1 print(time.ctime())
2 # 输出: Wed Dec 4 11:09:54 2019
gmtime()-------计算机可以处理的时间格式
1 print(time.gmtime())
2 #输出: time.struct_time(tm_year=2019, tm_mon=12, tm_mday=4, tm_hour=3, tm_min=11, tm_sec=11, tm_wday=2, tm_yday=338, tm_isdst=0)
时间格式化
%Y 年份
%m 月份
%B 月份名称 January
%b 月份名称缩写 Jan
%d 日期
%A 星期 Monday
%a 星期缩写 Mon
%H 小时 24
%h 小时 12
%p 上下午
%M 分钟
%S 秒
strftime()-------将时间进行合理输出
1 p = time.localtime()
2 print(time.strftime("%Y-%m-%d %H:%M:%S",p))
3 # 输出: 2019-12-04 03:11:11
4
5 print(time.strftime("%Y-%B-%d-%A-%H-%p-%S")
6 '2018-April-21-Saturday-16-PM-10'
7
8 print( time.strftime("%A-%p"))
9 'Saturday-PM'
10
11 print(time.strftime("%M:%S"))
12 '15:39'
strptime()-------自定义时间
题外: 格式化 输出昨天的日期
import datetime
t = datetime.datetime.now() + datetime.timedelta(days=-1)
p = t.strftime("%Y/%m/%d")
print(p)
# 输出 2021/07/11
程序计时
perf_counter()-------测量时间函数
1 import time
2
3 start = time.perf_counter()
4 time.sleep(0.5)
5 end = time.perf_counter()
6 print(end - start)
sleep()-------产生时间函数,s拟休眠的时间,单位是秒,可以是浮点数

浙公网安备 33010602011771号