欢迎访问宙启技术站
智能推送

Python time模块中的常用函数介绍

发布时间:2023-05-27 09:24:23

time模块是Python标准库中的一个模块,主要用于处理时间相关的计算和操作。在时间处理和日期计算方面,time模块提供了许多有用的函数,下面介绍一些常用的函数:

1. time.time()

该函数返回当前时间的时间戳(浮点型),即自1970年1月1日 00:00:00 UTC(世界标准时间)到现在所经过的秒数。

使用方法:

import time

print(time.time())

输出结果类似:1619182484.7356231

2. time.localtime([seconds])

该函数生成当前时间的struct_time对象,如果秒数参数为空,则使用当前时间。

使用方法:

import time

localtime = time.localtime()

print(localtime)

输出结果类似:time.struct_time(tm_year=2021, tm_mon=4, tm_mday=23, tm_hour=9, tm_min=53, tm_sec=36, tm_wday=4, tm_yday=113, tm_isdst=0)

3. time.gmtime([seconds])

该函数生成相应的UTC时间的 struct_time 对象,如果秒数参数为空,则使用当前时间。

使用方法:

import time

gmttime = time.gmtime()

print(gmttime)

输出结果类似:time.struct_time(tm_year=2021, tm_mon=4, tm_mday=23, tm_hour=9, tm_min=53, tm_sec=36, tm_wday=4, tm_yday=113, tm_isdst=0)

4. time.mktime(t)

该函数将struct_time类型的时间转换为时间戳(浮点型)格式。

使用方法:

import time

localtime = time.localtime()

print(localtime)

time_stamp = time.mktime(localtime)

print(time_stamp)

输出结果类似:

time.struct_time(tm_year=2021, tm_mon=4, tm_mday=23, tm_hour=9, tm_min=59, tm_sec=56, tm_wday=4, tm_yday=113, tm_isdst=0)

1619183996.0

5. time.asctime([t])

将struct_time格式的时间转换为字符串格式的时间。

使用方法:

import time

localtime = time.localtime()

print(localtime)

asctime = time.asctime(localtime)

print(asctime)

输出结果类似:Fri Apr 23 10:01:53 2021

6. time.strftime(format[, t])

将struct_time类型的时间转换为指定格式的字符串格式的时间。

使用方法:

import time

localtime = time.localtime()

print(localtime)

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

print(strftime)

输出结果类似:2021-04-23 10:03:40

7. time.sleep(secs)

该函数作用是使程序暂停执行一段时间,单位是秒。该函数成功运行后会暂停当前线程(程序中的执行流)指定的秒数。

使用方法:

import time

print("before sleep")

time.sleep(3)

print("after sleep")

输出结果类似:

before sleep

after sleep

8. time.process_time()

返回当前进程的CPU时间,单位是秒。

使用方法:

import time

print(time.process_time())

输出结果类似:18.16

以上介绍的是一些常用的time模块的函数,除此之外,time模块还有很多其他有用的函数,比如clock(), perf_counter(), monotonic()等。在使用时需要结合实际需求来进行选择使用。