使用python实现一个简单的时间戳和日期的相互转换
现在查询某个时间对应的时间戳方法很简单,直接百度一下:时间戳在线转换 即可搜到好多时间戳在线转换工具。但如果公司限制访问外网时,时间戳在线转换就无法使用,这时,可以利用python的内置模块time,来实现一个简单的时间戳和日期转换。
具体代码如下:
#encoding:utf-8 import time class TimeConvert(object): """ 时间格式转换 """ def timestamp_to_date(self,timestamp,format_date="%Y-%m-%d %H:%M:%S"): """ 时间戳转换为日期 @timestamp 需要转换的时间戳 @format_date 指定日期格式 %Y:年,%m:月,%d:日,%H:小时,%M:分组,%S:秒,默认格式:%Y-%m-%d %H:%M:%S """ try: # 判断时间戳类型为:秒 还是毫秒 if len(str(timestamp)) == 10: lt = time.localtime(timestamp) else: lt = time.localtime(timestamp/1000) date_value = time.strftime(format_date,lt) return {"时间戳":timestamp,"对应日期":date_value} except Exception as e: raise(e) def date_to_timestamp(self,date_value): """ 日期转成时间戳 @date_value 需要转换的日期,格式必须为:年-月-日 时:分:秒 """ try: t_tuple = time.strptime(date_value,"%Y-%m-%d %H:%M:%S") print(t) except Exception as e: raise("时间格式应为:年-月-日 时:分:秒") finally: return {"时间":date_value,"时间戳":int(time.mktime(t_tuple))} if __name__=="__main__": test = TimeConvert() print(test.timestamp_to_date(1720329139790,format_date="%Y-%m-%d")) print(test.date_to_timestamp("2024-07-07 12:16:13"))
运行结果:
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构