时间相关的模块
格式化好的时间 2020-05-16 18:10:20
时间戳 156854124141 从unix 元年,从计算机发明的那一年,到现在发生了多少秒,没过一秒加1
计算时间 用时间戳比较方便
获取时间
1 2 3 4 5 6 7 8 9 10 11 12 | print (time.time()) #获取当前时间的时间戳 print (time.strftime( '%Y-%m-%d %H:%M:%S' )) #获取当前时间的格式化时间,要指定格式 print (time.strftime( '%Y-%m' )) print (time.strftime( '%Y-%m-%d' )) print (time.strftime( '%Y/%m/%d' )) 运行结果: 1589625355.8514764 2020 - 05 - 16 18 : 35 : 55 2020 - 05 2020 - 05 - 16 2020 / 05 / 16 |
时间的互相转换,格式化好时间和时间戳之间不能直接转换,需要通过时间元组
1.时间戳转格式化时间
1 2 3 4 5 6 7 8 9 10 11 | import time,datetime result = time.localtime( 1589617159.785086 ) #把时间戳转换为时间元组 print (result) print (time.strftime( '%Y/%m/%d' ,result)) #将时间元组转为格式化的时间,可以指定格式 print (time.strftime( '%Y-%m-%d %H:%M:%S' ,result)) 运行结果: time.struct_time(tm_year = 2020 , tm_mon = 5 , tm_mday = 16 , tm_hour = 16 , tm_min = 19 , tm_sec = 19 , tm_wday = 5 , tm_yday = 137 , tm_isdst = 0 ) 2020 / 05 / 16 2020 - 05 - 16 16 : 19 : 19 |
2.格式化时间转时间戳
1 2 3 4 5 6 | import time,datetime result = time.strptime( '2020-05-16 16:19:19' , '%Y-%m-%d %H:%M:%S' ) #把时间戳转换为时间元组 print (time.mktime(result)) #将元组转成时间戳 运行结果: 1589617159.0 |
sleep等待多久之后再执行下面的代码
# time.sleep(10)
# print('等待10s后再运行')
以下是实现时间转换的函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import time,datetime def str_to_timezone( str = None , format = "%Y-%m-%d %H:%M:%S" ): #这个函数是格式化好的时间转时间戳的,如果不传参数默认返回当前时间戳 if str : time_tuple = time.strptime( str , format ) result = time.mktime(time_tuple) else : result = time.time() return int (result) print (str_to_timezone( '2020-05-16 16:19:19' )) def timezone_to_str(timezone = None , format = "%Y-%m-%d %H:%M:%S" ): '''这个函数是时间戳转格式化好的时间,如果不传参数,默认返回当前时间''' if timezone: time_tuple = time.localtime(timezone) result = time.strftime( format ,time_tuple) else : result = time.strftime( format ) return result print (timezone_to_str( 1589617159 )) 运行结果: 1589617159 2020 - 05 - 16 16 : 19 : 19 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2017-05-16 Python中基本的读文件和简单数据处理
2017-05-16 上传和下载文件
2017-05-16 fiddler与Charles的区别
2017-05-16 修改请求和返回报文
2017-05-16 charles抓包--手机端