python datetime, timestamp,字符串类型时间之间的转换
作者:互联网
import time
from datetime import datetime
from cffi.backend_ctypes import long
def str_to_datetime(time_str):
'''
把格式化的字符串类型的时间转换成datetime格式
:param time_str: '2022-06-13 20:21:04.242'
:return: datetime类型
'''
date_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%f")
return date_time
def datetime_to_stamp(date_time):
'''
将datetime格式的时间(含毫秒)转为毫秒时间戳
:param date_time: {datetime} '2022-06-13 20:21:04.242'
:return: 13位的毫秒时间戳
'''
time_stamp = long(time.mktime(date_time.timetuple()) * 1000.0 + date_time.microsecond / 1000.0)
return time_stamp
def time_str_to_stamp(time_str):
'''
把格式化的字符串类型的时间转换成13位的时间戳
:param time_str: '2022-06-13 20:21:04.242'
:return: 13位的毫秒时间戳
'''
date_time = str_to_datetime(time_str)
time_stamp = datetime_to_stamp(date_time)
return time_stamp
def stamp_to_time_str(stamp):
'''
把13位的时间戳转换为格式化的字符串类型的时间
:param stamp:
:return:
'''
str_time = datetime.fromtimestamp(stamp / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
return str_time
if __name__ == '__main__':
print(stamp_to_time_str(1655176900265))
print(time_str_to_stamp('2022-06-09 10:37:30.122'))
标签:return,python,timestamp,datetime,stamp,str,time,date 来源: https://www.cnblogs.com/stxz/p/16379784.html