一、什么是Unix时间戳
1、Unix时间戳是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。
2、Unix时间戳有秒级和毫秒级
3、实用工具传送门 → Unix时间戳和北京时间在线转换工具
二、使用的模块
1、常使用的是 datetime 模块中的 datetime 类
from datetime import datetime
2、datetime 对象:年-月-日 时:分:秒.小数(秒)
datetime(year, month, day, hour, minute, second,microsecond, tzinfo=None)
三、代码演示
# Unix 时间戳转北京时间(字符串)函数
def UnixToDatetimeStr(Unix):
Value = int(Unix / 1000)
date_str = str(Value)
print("date_str ", date_str)
print("len ", len(date_str))
# 毫秒级时间戳
if len(date_str) == 10:
intValue = Unix / 1000
# 秒级时间戳
elif len(date_str) == 7:
intValue = Unix
else:
return -1
print("intValue ", intValue)
# 将时间戳转换成datetime对象
timetamp = datetime.fromtimestamp(intValue)
# 按设定的时间格式生成时间字符串
# 显示秒数的小数位
datetimeValue = timetamp.strftime("%Y-%m-%d %H:%M:%S.%f")
# # 不显示秒数的小数位
# datetimeValue = timetamp.strftime("%Y-%m-%d %H:%M:%S")
print("datetimeValue ", datetimeValue)
return datetimeValue
################# 转换Code Start ###################
# # Unix时间戳(s)
# timeValue = 1709792418.061697
# Unix时间戳(ms)
timeValue = 1709792418061.697
datetime = UnixToDatetimeStr(timeValue)
print("datetime ", datetime)
################# 转换Code End #####################
四、运行结果
1、Unix时间戳(s):1709792418.061697
2、Unix时间戳(ms):1709792418061.697
五、结论
1、此代码支持两种Unix时间戳(秒/毫秒)转换北京时间字符串
2、可设定时间字符串的输出格式,上述代码可以选显示秒小数位或不显示
3、此代码在国内运行,未考虑时区,对这方面感兴趣的。可以在评论区一起讨论~
- 欢迎纠正,(づ ̄3 ̄)づ╭❤~
如果有帮助到你,能点个赞吗?ღ( ´・ᴗ・` ) 比心