当前位置: 首页> 科技> 能源 > Python 时间和时间戳相互转换

Python 时间和时间戳相互转换

时间:2025/7/8 21:14:02来源:https://blog.csdn.net/yudiandian2014/article/details/139859196 浏览次数:0次
import typing as t
import time
import datetime"""
原文:
python时间相互转换
https://py-code.readthedocs.io/zh/latest/Python/time_utils/index.html
""""""
# 1.1. 时间字符串转换为13位时间戳
# 1.2. 时间字符串转换为datetime
# 1.3. 时间戳转换为时间字符串
# 1.4. 时间戳转换为datetime对象
# 1.5. datetime对象转换为时间字符串
# 1.6. datetime对象转换为13位时间戳
"""# 1.1. 时间字符串转换为13位时间戳
def str_to_timestamp(str_time: str, time_format: str = "%Y-%m-%d %H:%M:%S") -> int:"""时间字符串转换为13位时间戳:param str_time: 时间字符串:param time_format: 时间字符串格式 default: %Y-%m-%d %H:%M:%Sexample: %Y-%m-%d:return: 13位时间戳Usage::>>> str_to_timestamp("2022-10-10", "%Y-%m-%d")1665331200000>>> str_to_timestamp("2022-10-10 10:10:10")1665367810000"""try:time_array = time.strptime(str_time, time_format)return int(time.mktime(time_array)) * 1000except ValueError:raise ValueError("Invalid time format!")# 1.2. 时间字符串转换为datetime
def str_to_datetime(str_time: str) -> datetime.datetime:"""时间字符串转换为datetime:param str_time: 时间字符串 格式为"2022-10-10 10:10:10" 或 "2022-10-10":return: datetime对象Usage::>>> str_to_datetime("2022-10-10 10:10:10")2022-10-10 10:10:10>>> str_to_datetime("2022-10-10")2022-10-10 00:00:00"""try:if " " in str_time:return datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")else:return datetime.datetime.strptime(str_time, "%Y-%m-%d")except ValueError:raise ValueError("Invalid time format!")# 1.3. 时间戳转换为时间字符串
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(1665331200000, "%Y-%m-%d")2022-10-10>>> timestamp_to_str(1665367810000)2022-10-10 10:10:10"""try:datetime_type = datetime.datetime.fromtimestamp(timestamp // 1000)return datetime_type.strftime(time_format)except (TypeError, ValueError):raise ValueError("Invalid timestamp format!")# 1.4. 时间戳转换为datetime对象
def timestamp_to_datetime(timestamp: t.Union[int, float]) -> datetime.datetime:"""时间戳转换为datetime对象:param timestamp: 时间戳:return: datetime对象Usage::>>> timestamp_to_datetime(1645513117000)2022-02-22 14:58:37>>> timestamp_to_datetime(1429417200.0)2015-04-19 12:20:00"""try:# 13位时间戳 毫秒格式转换if len(str(int(timestamp))) == 13:return datetime.datetime.fromtimestamp(timestamp // 1000)return datetime.datetime.fromtimestamp(timestamp)except ValueError:raise ValueError("Invalid time format!")# 1.5. datetime对象转换为时间字符串
def datetime_to_str(datetime_obj: datetime.datetime) -> str:"""datetime对象转换为时间字符串:param datetime_obj: datetime对象:return: 时间字符串Usage::>>> datetime_to_str(datetime.datetime.now()))2022-02-22 14:46:04"""try:return datetime_obj.strftime("%Y-%m-%d %H:%M:%S")except AttributeError:raise ValueError("Invalid time format!")# 1.6. datetime对象转换为13位时间戳
def datetime_to_timestamp(datetime_obj: datetime.datetime) -> int:"""datetime对象转换为13位时间戳:param datetime_obj: datetime对象:return: 13位时间戳Usage::>>> datetime_to_timestamp(datetime.datetime.now()))1645513117000"""try:return int(datetime_obj.timestamp()) * 1000except AttributeError:raise ValueError("Invalid time format!")

调用:


# 1.1. 时间字符串转换为13位时间戳
print(str_to_timestamp("2022-10-10", "%Y-%m-%d"))
print(str_to_timestamp("2022-10-10 10:10:10"))
'''
输出:
1665331200000
1665367810000
'''# 1.2. 时间字符串转换为datetime
print(str_to_datetime("2022-10-10 10:10:10"))
print(str_to_datetime("2022-10-10"))
'''
输出:
2022-10-10 10:10:10
2022-10-10 00:00:00
'''# 1.3. 位时间戳转换为时间字符串
print(timestamp_to_str(1665331200000, "%Y-%m-%d"))
print(timestamp_to_str(1665367810000))
'''
输出:
2022-10-10
2022-10-10 10:10:10
'''# 1.4. 时间戳转换为datetime对象
print(timestamp_to_datetime(1645513117000))
print(timestamp_to_datetime(1429417200.0))
'''
输出:
2022-02-22 14:58:37
2015-04-19 12:20:00
'''# 1.5. datetime对象转换为时间字符串
print(datetime_to_str(datetime.datetime.now()))
'''
输出:
2024-06-21 13:43:46
'''# 1.6. datetime对象转换为13位时间戳
print(datetime_to_timestamp(datetime.datetime.now()))
'''
输出:
1718948690000
'''

关键字:Python 时间和时间戳相互转换

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: