Day20【time模块】
time模块
1.time.time()
time.time()会返回当前时间的时间戳,时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。注意time.time()的括号内没有参数:
import timecurrent_time = time.time()
print(current_time) # 输出当前时间的时间戳,以秒为单位
2.import time
current_time = time.time()
print(current_time) # 输出当前时间的时间戳,以秒为单位
import timecurrent_time = time.localtime() # 获取当前时间的结构化时间对象
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
print(formatted_time) # 格式化时间输出
# 2023-12-17 18:57:29
3.time.ctime
time.ctime([sec])可以将时间戳的秒数转换字符串的时间格式:
import timetimestamp = 1639699861
converted_time = time.ctime(timestamp)
print(converted_time) # 将时间戳转换为可读形式的时间字符串
# Fri Dec 17 08:11:01 2021
4.time.sleep()
import timeprint("Start")
time.sleep(2) # 暂停程序执行 2 秒钟
print("End")
利用time模块制作简易定时启动项目
# 时间戳
now_w = time.localtime().tm_wday + 1 # 周
now_h = time.localtime().tm_hour # 时
now_m = time.localtime().tm_min # 分# 一个简易可视化倒计时模块
def countdown_boss(s):for i in range(s, 0, -1):s = '\r距离开始boss还有:%d秒' % iprint(s.ljust(3), end='', flush=True)time.sleep(1)print("开始boss活动")# 计算距离t时间还有多少秒
def wait_boss(t):now = datetime.now()print(now)mark = now.replace(hour=t, minute=5, second=0)spt = mark - nowreturn int(spt.total_seconds())# 判断今天是周几并且等待一定时间后自动启动任务
def daily_boss():# 门派bossif now_w in [2, 4, 6]:now_h = time.localtime().tm_hour # 时if now_h >= 12 and now_m >= 5:spt = wait_boss(20)# time.sleep(spt)countdown_boss(spt)