Python 时间戳转时间

一、 10 位 时间戳 ,秒级 转换为时间

方式一:

python 复制代码
import time

timeStamp = 1717149862
timeArray = time.localtime(timeStamp)
timeStr = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(timeStr)

'''
输出:
2024-05-31 18:04:22
'''

方式二:

python 复制代码
import datetime

timeStamp = 1717149862
dateArray = datetime.fromtimestamp(timeStamp)
timeStr = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(timeStr)

# 转换为 UTC 时间,相差8小时
timeStamp = 1717149862
dateArray = datetime.utcfromtimestamp(timeStamp)
timeStr = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(timeStr) 


'''
输出:
2024-05-31 18:04:22
2024-05-31 10:04:22
'''

二、 13位时间戳转换为时间字符串

方式一:

python 复制代码
from datetime import datetime

def timestamp_to_strtime(timestamp: int):
    """将 13 位整数的毫秒时间戳转化成本地普通时间 (字符串格式)
    :param timestamp: 13 位整数的毫秒时间戳 (1717149892810)
    :return: 返回字符串格式 {str} '2024-05-31 18:03:41'
    """
    timeArray =  datetime.fromtimestamp(timestamp / 1000.0)
    strtime =timeArray.strftime('%Y-%m-%d %H:%M:%S.%f')  # .%f 带不带都可
    return strtime

timeStr = timestamp_to_strtime(1717149892810)
print(timeStr)


'''
输出:
2024-05-31 18:04:52.810000
'''

方式二:

python 复制代码
import datetime

def timestamp_to_str(timestamp: int, time_format: str = "%Y-%m-%d %H:%M:%S") -> str:
    """
    时间戳转换为时间字符串
    :param timestamp: 时间戳
    :param time_format: 时间字符串格式 default: %Y-%m-%d %H:%M:%S
    :return: 时间字符串
    Usage::
      >>> timestamp_to_str(1717149892810, "%Y-%m-%d")
      2024-05-31
      >>> timestamp_to_str(1717149892810)
      2024-05-31 18:04:52
      >>> timestamp_to_str(1717149892810, "%Y-%m-%d %H:%M:%S.%f")
      2024-05-31 18:04:52.000000

    """
    try:
    	# 13 位 时间戳,毫秒级
        datetime_type = datetime.datetime.fromtimestamp(timestamp // 1000)
        # 10 位 时间戳,秒级
        # datetime_type = datetime.datetime.fromtimestamp(timestamp)
        return datetime_type.strftime(time_format)
    except (TypeError, ValueError):
        raise ValueError("Invalid timestamp format!")

timeStr = timestamp_to_str(1717149892810)
print(timeStr)


'''
输出:
2024-05-31 18:04:52
'''

'''

参考:

时间戳转换

https://tool.lu/timestamp/

Python3日期与时间戳转换的几种方法

https://zhuanlan.zhihu.com/p/67950661

Python时间戳和时间类型及其互相转换

https://www.cnblogs.com/sablier/p/14251436.html

【python】 datetime、13位和10位时间戳、字符串的相互转换

https://blog.csdn.net/weixin_42221654/article/details/131477857

python时间相互转换

https://py-code.readthedocs.io/zh/latest/Python/time_utils/index.html

'''

相关推荐
matlabgoodboy13 分钟前
程序代做python代编程matlab定制代码编写C++代写plc设计java帮做
c++·python·matlab
副露のmagic40 分钟前
更弱智的算法学习 day34
python·学习
AllFiles1 小时前
用Python turtle画出标准五星红旗,原来国旗绘制有这么多数学奥秘!
python
亲爱的非洲野猪1 小时前
Java线程池深度解析:从原理到最佳实践
java·网络·python
用户1377940499931 小时前
基于遗传算法实现自动泊车+pygame可视化
python
4***17541 小时前
强化学习中的蒙特卡洛方法
python
pen-ai1 小时前
打通 Python 与 C++ 的参数传递机制
开发语言·c++·python
至此流年莫相忘1 小时前
Python之深拷贝和浅拷贝
python
像风一样自由20202 小时前
XGBoost、LightGBM、CatBoost 原理深度剖析与全面对比
python
用户230826676652 小时前
Python的管道符(|)联合类型语法糖
python