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