博客
关于我
Python 基础 - Day 5 Learning Note - 模块 之 标准库:time (1)
阅读量:796 次
发布时间:2023-03-07

本文共 2035 字,大约阅读时间需要 6 分钟。

Python下的时间处理

在Python中,time模块提供了丰富的功能来处理和格式化时间信息。以下是对时间表示方式的详细说明。

1. 时间戳(timestamp)

时间戳是从1970年1月1日开始的秒数偏移量,以float数据类型呈现。它是计算机时代最常用的时间表示方式之一。Python中常用的获取时间戳的函数包括time()clock()等。

print(time.time())  # 返回当前时间的时间戳

2. struct_time元祖

struct_time元祖是time模块中的一种数据结构,用于表示具体的时间信息。常用的获取struct_time元祖的函数包括gmtime()localtime()strptime()。元祖包含以下9个元素:

索引 属性 值范围
0 tm_year 年份(例如2011)
1 tm_mon 月份(1-12)
2 tm_mday 天(1-31)
3 tm_hour 小时(0-23)
4 tm_min 分钟(0-59)
5 tm_sec 秒(0-61)
6 tm_wday 星期(0-6,0为周日)
7 tm_yday 年内的第几天(1-366)
8 tm_isdst 夏令时标志(-1表示未知)

需要注意的是,tm_isdst的值取决于系统的时区设置。

3. 时间字符串格式化与解析

在Python中,可以使用格式化字符串将时间转换为特定的字符串表示,或者将字符串解析为时间元祖。常用的格式化字符包括:

格式字符 含义
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化月份名称
%B 本地完整月份名称
%c 本地日期和时间表示
%d 一个月中的第几天(01-31)
%H 一天中的小时(24小时制,00-23)
%I 一天中的小时(12小时制,01-12)
%j 一年中的第几天(001-366)
%m 月份(01-12)
%M 分钟(00-59)
%p AM/PM标志(与%I配合使用)
%S 秒(01-61)
%U 年内的星期数(00-53)
%w 星期内的天数(0-6,0为星期天)
%W 星期内的天数(与%U类似,但一周从星期一开始)
%x 本地日期字符串
%X 本地时间字符串
%y 去掉世纪的年份(00-99)
%Y 完整的年份
%Z 时区名称
%% %%符号

例如,可以使用以下代码将一个时间戳格式化为特定的字符串:

from time import time, strftimetimestamp = time()  # 获取当前时间戳formatted_time = strftime("%Y-%m-%d %X", timestamp)print(formatted_time)  # 输出类似“2023-10-10 12:34:56”

4. 常用操作

以下是time模块中一些常用的函数和操作:

import time# 获取当前时间的struct_time元祖current_time = time.localtime()print(current_time)  # 输出类似时间元祖# 将时间戳转为struct_time元祖timestamp = 1304575584.1361799local_time = time.localtime(timestamp)print(local_time)  # 输出对应的struct_time元祖# 获取当前时间的时间戳current_timestamp = time.time()print(current_timestamp)# 获取与当前时间的时间戳差异time_difference = time.time() - current_timestampprint(time_difference)# 将struct_time元祖转为时间戳time_tuple = (2019, 2, 15, 10, 13, 38, 1, 48, 0)formatted_timestamp = time.mktime(time_tuple)print(formatted_timestamp)# 将时间戳转为“YYYY-MM-DD HH:MM:SS”格式的字符串formatted_string = time.strftime("%Y-%m-%d %X", time.localtime())print(formatted_string)# 将字符串转为struct_time元祖time_string = "2011-05-05 16:37:06"parsed_time = time.strptime(time_string, "%Y-%m-%d %X")print(parsed_time)# sleep函数用于线程延迟time.sleep(1)  # 线程延迟1秒

通过以上方法,可以方便地在Python程序中处理各种时间相关的需求。

转载地址:http://znofk.baihongyu.com/

你可能感兴趣的文章
Python 中读取 CSV 文件-ChatGPT4o作答
查看>>
Python 之 filecmp
查看>>
python请求html_使用Python请求获取HTML?
查看>>
Python 之匿名函数和偏函数
查看>>
python 之栈的实现
查看>>
python语音播放
查看>>
python语言:装饰器原理
查看>>
Python 交互式数据可视化详解
查看>>
python语言有哪些优点和缺点_Python有哪些优缺点,你了解吗?
查看>>
Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
查看>>
Python 从数据库中存储和检索密码的最安全方法
查看>>
Python语言及其应用 - 知识点遍历
查看>>
Python 优化提速的 8 个小技巧
查看>>
Python 余弦相似度与皮尔逊相关系数 计算
查看>>
python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
查看>>
python 使用filetype校验文件
查看>>
Python 使用flush函数将缓冲区数据立即写磁盘
查看>>
python 使用in判断不准确,in不好使
查看>>
Python 使用pandas 进行查询和统计详解
查看>>
Redis 配置文件redis.conf详细解释
查看>>