Python中time库的使用(日期时间)
作者:emanlee 时间:2022-11-12 09:04:23
time库是python中处理时间的标准库。
计算机时间的表达:time()、ctime()、gmtime();
提供获取系统时间并格式化输出功能: strftime()、strptime()
提供系统级精确计时功能可用于程序性能分析: sleep()、perf_counter()
时间获取 time.time(): 获取当前时间戳,即计算机内部时间值,浮点数
>>> import time
>>> time.time()
1655598609.7932513
time.ctime(): 获取当前时间并以一种易读的形式表示,返回字符串
>>> import time
>>> time.ctime()
'Sun Jun 19 08:31:03 2022'
time.gmtime(): 获取当前时间,表示为计算机可以处理的时间格式
>>> import time
>>> time.gmtime()
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=19, tm_hour=0, tm_min=31, tm_sec=56, tm_wday=6, tm_yday=170, tm_isdst=0)
时间格式化将计算机内部表达的年月日时分秒等与时间有关的信息,用一种变量的形式合理组合并且合理输出,通过控制表达输出格式,展示模板由特定的格式化控制符组成。
time.strftime(tpl , ts) tpl是格式化模板字符串,用于定义输出效果 ; ts是计算机内部时间类型变量
时间格式化,指strftime的tpl部分
>>> import time
>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2022-06-19 08:33:33
time.strptime(str,tpl) 反格式化-将时间字符串编程计算机内部可以操作的时 str是字符串形式的时间值;tpl是格式化模板字符串,用来定义输出效果。
>>> import time
>>> print(time.strptime("2020-12-15","%Y-%m-%d"))
time.struct_time(tm_year=2020, tm_mon=12, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=350, tm_isdst=-1)
>>> import time
>>> print(time.localtime())
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=19, tm_hour=8, tm_min=39, tm_sec=36, tm_wday=6, tm_yday=170, tm_isdst=0)
程序计时应用测量起止动作所经历时间的进程。
测量时间:time.perf_counter()
#导入时间模块
import time
#求素数的程序
def is_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
if __name__ == '__main__':
number = 17377
start_time = time.perf_counter()
is_prime(number)
end_time = time.perf_counter()
#按差异打印执行时间
print(end_time - start_time)
产生时间:time.sleep(s) s是拟休眠的时间,单位是秒,可以是浮点数。
REF
https://baijiahao.baidu.com/s?id=1728816399629285523&wfr=spider&for=pc
https://baijiahao.baidu.com/s?id=1685495648757727003&wfr=spider&for=pc
https://www.nhooo.com/note/qa0bhu.html
来源:https://www.cnblogs.com/emanlee/p/16389886.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Golang实现带优先级的select
![](https://img.aspxhome.com/file/2023/5/133935_0s.png)
django之对FileField字段的upload_to的设定方法
利用Python正则表达式过滤敏感词的方法
![](https://img.aspxhome.com/file/2023/0/95310_0s.jpg)
python中字典和列表的相互嵌套问题详解
Apache SkyWalking 监控 MySQL Server 实战解析
![](https://img.aspxhome.com/file/2023/0/115360_0s.png)
python实现按关键字筛选日志文件
高质量Python代码编写的5个优化技巧
vue+iview实现手机号分段输入框
![](https://img.aspxhome.com/file/2023/2/133132_0s.jpg)
安装MySQL后include目录下没有找到libmysql.lib
卸载tensorflow-cpu重装tensorflow-gpu操作
![](https://img.aspxhome.com/file/2023/0/131650_0s.jpg)
Go高级特性探究之对象比较详解
python排序的方法实例总结
Bootstrap中的表单验证插件bootstrapValidator使用方法整理(推荐)
![](https://img.aspxhome.com/file/2023/1/136951_0s.jpg)
按钮表状态还是表动作?
![](https://img.aspxhome.com/file/UploadPic/20093/23/1-300x272-42s.jpg)
php自动获取字符串编码函数mb_detect_encoding
AJAX无刷新验证用户名是否存在
JavaScript 数组中最大最小值
Vue用v-for给循环标签自身属性添加属性值的方法
![](https://img.aspxhome.com/file/2023/3/139773_0s.png)
用户 jb51net 登录失败。原因: 该帐户的密码必须更改
提升设计品质的8个布局方案[译]
![](https://img.aspxhome.com/file/UploadPic/20103/18/01-33s.jpg)