使用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"))
复制代码

运行结果:

 

posted @   西夏一品唐  阅读(179)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示