Python 时间和时间戳相互转换

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:%S
           example: %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)) * 1000
    except 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()) * 1000
    except 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
'''

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值