使用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 @ 2024-07-07 13:59  西夏一品唐  阅读(19)  评论(0编辑  收藏  举报