python 的时间函数
python 时间处理的基本格式是以元组封装的结构化时间,其格式可参考Python 日期和时间,常用的函数如下:
一、读取到结构化时间
# 将字符串读取到结构化时间(支持多种格式的时间字符串,详见[strptime()](https://www.runoob.com/python/att-time-strptime.html))
struct_time = time.strptime("2022-03-18 10:54:00", '%Y-%m-%d %H:%M:%S')
struct_time = time.strptime("30 Nov 00", "%d %b %y")
# 将时间戳读取到结构化时间,时间戳是以标准 UTC 时间为基准,是本初子午线 1970-01-01 00:00:00 流逝的秒数
time_stamp = 1
struct_time = time.gmtime(time_stamp) # 得到 1970-01-01 00:00:01
struct_time = time.localtime(time_stamp) # 得到 1970-01-01 08:00:01
二、结构化时间输出为其他格式
time_stamp = 1640844000
struct_time = time.localtime(time_stamp)
# 结构化时间输出为字符串
time_str = time.strftime('%Y-%m-%d %H:%M:%S', struct_time)
# 结构化时间转换成时间戳
timestamp = time.mktime(struct_time)
三、获取当前年月日
import datetime
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
# 格式化输出,strftime 函数不支持中文,可使用以下代码格式化日期时间
str = f"{now.year}年{now.month}月{now.day}日"
四、获取时间差
import datetime
start = datetime.datetime.now()
# Do something ...
# str(timedelta) 的显示格式类似 "0:01:12.38214",如果需要其它自定义格式,需要自己写代码转换
print(f"耗时:{str(datetime.datetime.now() - start)}"

浙公网安备 33010602011771号