python--Time(时间)模块

要使用一个模块,首先要把模块导入进来

import time

我们先把这一篇文章需要用的模块导入进来

首先说一下time模块,time模块中的函数

--sleep:休眠指定的秒数(可以是小数)

import time
print("开始")
time.sleep(5)
print("结束")
#如果在pycharm中输入这段代码,从开始到结束,中间会停留5秒,sleep后面的括号里面填的数字就是秒数

--time:获取时间戳

import time
t = time.time()
print(t)
#这段代码是获取时间戳(从1970-01-01 00:00:00到你输入代码运行时的秒数)

--localtime:将时间戳转换为对象

import time
local_time = time.localtime() print(local_time) #会打印出此时此刻的年月日时分秒 print(local_time.tm_year) #指定输出对应的年份 print(local_time[0]) #也可以指定下标输出年份

mktime:根据年月日等信息转换为时间戳

import time
new_time = time.mktime((2099, 9, 9, 10, 10, 10, 1, 212, 0)) #上面括号里面是填写自定义的时间,要写够9个数字 print(new_time) #输出的时1970-01-01 00:00:00到自定义时间的秒数

gmtime:功能同localtime

import time
gt = time.gmtime() print(gt) #输出当前时间的年月日时分秒

timezone:0时区到你所在的时区的相差秒数(/3600 = 小时)

import time
print
(time.timezone/3600) #我所在的是东8区,所以输出的是-8.0

strftime:将time.struct_time对象格式化显示

import time
local_time = time.localtime() # 格式化显示 print(time.strftime('%Y-%m-%d %H:%M:%S', local_time)) #规定输出的格式 print(time.strftime('%D', local_time)) #\D是一种特定的显示格式 月/日/年 #%Y:年(4位), %y:年(2位), %m:月, %d:日, %D:月/日/年, %H:时 #%M:分, %S:秒, %w:星期(1~7), %W:本周是今年的第几周 # 特定的显示格式 print(time.asctime()) #格式输出当前的时间

猜你喜欢

转载自www.cnblogs.com/ilovezzh/p/9446024.html