python --格式化时间转时间戳(互转)

import time
import datetime

class TimesType(object):
    '''时间格式互转'''

    def __new__(cls, *args, **kwargs):
        '''单例模式'''
        if not hasattr(cls, '_instance'):
            orig = super(TimesType, cls)
            cls._instance = orig.__new__(cls)
        return cls._instance

    @staticmethod
    def from_strtime_inttime(t: str) -> int:
        '''转为时间戳'''
        return int(time.mktime(time.strptime(t, "%Y-%m-%d %H:%M:%S")))

    @staticmethod
    def from_inttime_strtime(t: int) -> str:
        '''转格式化时间'''
        # return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t))  # time
        return datetime.datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S")  # datetime

    @staticmethod
    def from_strtime_format_strtime(t: str) -> str:
        '''转显示格式'''
        return time.strftime("%Y/%m/%d %H:%M:%S", time.strptime(t, "%Y-%m-%d %H:%M:%S"))

	@staticmethod
    def from_strtime_format_datetime(t: str) -> datetime:
        '''字符串时间格式转datetime格式'''
        return time.strptime(t, "%Y-%m-%d %H:%M:%S")


    def __str__(self) -> str:
        return '时间格式互转'

datetime将datetime对象转换成时间字符串和时间戳

# datetime对象转换成时间字符串
datetime_str = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
print(datetime_str)
 
# datetime对象转换成时间戳
datetime_stamp = datetime.timestamp(datetime.now())
print(datetime_stamp)

结果

2019-05-29 17:22:37
1559121757.343784

datetime将时间字符串转换成时间戳

# 时间字符串转datetime对象,再转时间戳
datetime_stamp2 = datetime.timestamp(datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S'))
print(datetime_stamp2)

输出:
1559121757.0

datetime将时间戳转换成时间字符串

# 时间戳转datetime对象,再转时间字符串
datetime_str2 = datetime.strftime(datetime.fromtimestamp(datetime_stamp2), '%Y-%m-%d %H:%M:%S')
print(datetime_str2)

输出:
2019-05-29 17:22:37
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

像风一样的男人@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值