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

Python时间模块函数使用详解

发布时间:2023-06-03 14:42:39

Python时间模块是Python标准库中的一个模块,用于处理时间和日期相关的操作。本文将介绍Python时间模块中常用的函数,并提供一些使用示例。

1. 时间戳

时间戳是自1970年1月1日以来经过的秒数。可以使用time模块中的time()函数获取当前时间的时间戳。

import time

now = time.time()
print(now)

输出以下内容:

1567096661.94838

2. 获取当前时间

可以使用time模块中的localtime()函数获取当前本地时间。

import time

now = time.localtime()
print(now)

输出以下内容:

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=29, tm_hour=10, tm_min=24, tm_sec=23, tm_wday=3, tm_yday=241, tm_isdst=0)

可以看到,localtime()函数返回了一个struct_time对象,它包含了当前时间的年、月、日、时、分、秒等信息。

3. 获取格式化时间

可以使用time模块中的strftime()函数将struct_time对象转换为指定格式的字符串。

import time

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

输出以下内容:

2019-08-29 10:24:23

4. 将字符串转换为struct_time对象

可以使用time模块中的strptime()函数将字符串转换为struct_time对象。

import time

str_time = "2019-08-29 10:24:23"
struct_time = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
print(struct_time)

输出以下内容:

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=29, tm_hour=10, tm_min=24, tm_sec=23, tm_wday=3, tm_yday=241, tm_isdst=-1)

5. 获取时间间隔

可以使用time模块中的mktime()函数将struct_time对象转换为时间戳,然后计算时间间隔。

import time

start_time = "2019-08-28 00:00:00"
end_time = "2019-08-29 10:24:23"

start_struct_time = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
end_struct_time = time.strptime(end_time, "%Y-%m-%d %H:%M:%S")

start_timestamp = time.mktime(start_struct_time)
end_timestamp = time.mktime(end_struct_time)

interval = end_timestamp - start_timestamp
print(interval)

输出以下内容:

93763.0

6. 获取时间戳的指定格式时间

可以使用time模块中的strftime()函数将时间戳转换为指定格式的字符串。

import time

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

输出以下内容:

2019-08-29 13:37:41

总结

本文介绍了Python时间模块中常用的函数,包括获取时间戳、获取当前时间、获取格式化时间、将字符串转换为struct_time对象、获取时间间隔以及获取时间戳的指定格式时间等。这些函数可以方便地处理时间和日期相关的操作。