python时间戳转日期格式(保留毫秒级别)

时间戳是一种保存便捷,后续可用来在其它编程语言下快速转换为日期格式的一种时间形式。

这里来说说如何通过 Python 将时间戳转换为日期格式。Python 拥有大量的库,其中不乏有对时间处理的库,这里介绍和使用到的是 Python 中最常见的两个时间库——time、datetime

通过 time.time() 可以获得当下时刻的时间戳:1594907094.8940988

时间戳在 time 下的返回值为 float 类型,如果后续你的时间戳为 str 类型,需要将其转换为数值类型再进行下一步的日期转换。

封装了一个小函数来处理转换过程:

import time
import datetime

# 正确10位长度的时间戳可精确到秒,11-14位长度则是包含了毫秒
def intTodatetime(intValue):
	if len(str(intValue)) == 10:
		# 精确到秒
		timeValue = time.localtime(intValue)
		tempDate = time.strftime("%Y-%m-%d %H:%M:%S", timeValue)
		datetimeValue = datetime.datetime.strptime(tempDate, "%Y-%m-%d %H:%M:%S")
	elif 10 <len(str(intValue)) and len(str(intValue)) < 15:
		# 精确到毫秒
		k = len(str(intValue)) - 10
		timetamp = datetime.datetime.fromtimestamp(intValue/(1* 10**k))
		datetimeValue = timetamp.strftime("%Y-%m-%d %H:%M:%S.%f")
	else:
		return -1
	return datetimeValue

time1 = 1594823552
time2 = 1594823552855
print(intTodatetime(time1))
print(intTodatetime(time2))

# 2020-07-15 22:32:32
# 2020-07-15 22:32:32.855000​

猜你喜欢

转载自blog.csdn.net/qq_36523839/article/details/107394697