杰瑞科技汇

Python中convertmillis函数如何使用?

Python 的标准库中没有一个叫做 convertmillis 的内置函数,这个名称通常是我们自己为实现某个功能而编写的函数名,或者是在其他编程语言/库中看到的函数。

Python中convertmillis函数如何使用?-图1
(图片来源网络,侵删)

在 Python 中,处理时间相关的核心模块是 timedatetime,我们将围绕这两个模块来展示如何实现“毫秒转换”的功能。

核心概念

  1. 时间戳:通常指自 1970 年 1 月 1 日 00:00:00 UTC(纪元时间)以来经过的秒数,这是一个浮点数。
  2. 毫秒时间戳:同样是自纪元时间以来的经过时间,但单位是毫秒,它是一个整数。
  3. time 模块:主要用于处理时间戳和格式化时间,与 C 语言库绑定,功能相对底层。
  4. datetime 模块:提供了更高级、更面向对象的日期和时间操作方式,通常更推荐使用。

使用 time 模块

time 模块非常适合快速将时间戳转换为字符串。

将毫秒时间戳转换为格式化字符串

这是最常见的需求。time.strftime() 函数需要一个以秒为单位的时间戳,我们需要先将毫秒除以 1000。

import time
# 假设我们有一个毫秒时间戳
#  1678886400000 对应 2025-03-15 00:00:00 UTC
millis_timestamp = 1678886400000
# 1. 将毫秒转换为秒
seconds_timestamp = millis_timestamp / 1000.0
# 2. 使用 time.localtime() 将秒时间戳转换为本地时间的 struct_time 对象
#    或者使用 time.gmtime() 转换为 UTC 时间
local_time_struct = time.localtime(seconds_timestamp)
# 3. 使用 time.strftime() 将 struct_time 格式化为字符串
#    %Y: 年, %m: 月, %d: 日, %H: 时, %M: 分, %S: 秒
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time_struct)
print(f"原始毫秒时间戳: {millis_timestamp}")
print(f"转换后的本地时间: {formatted_time}")
# 如果想获取 UTC 时间
utc_time_struct = time.gmtime(seconds_timestamp)
formatted_utc_time = time.strftime("%Y-%m-%d %H:%M:%S", utc_time_struct)
print(f"转换后的UTC时间: {formatted_utc_time}")

输出:

Python中convertmillis函数如何使用?-图2
(图片来源网络,侵删)
原始毫秒时间戳: 1678886400000
转换后的本地时间: 2025-03-15 08:00:00  # 注意:时区不同,时间会不一样
转换后的UTC时间: 2025-03-15 00:00:00

获取包含毫秒的精确时间字符串

time.strftime() 本身不支持毫秒,要获取毫秒,我们需要从 time.time() 获取当前时间的浮点数部分。

import time
# 获取当前时间的秒时间戳(浮点数,包含小数部分,即毫秒/微秒)
current_seconds = time.time()
# 将秒时间戳转换为 struct_time
current_time_struct = time.localtime(current_seconds)
# 格式化到秒
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time_struct)
# 获取毫秒部分 (将小数部分乘以1000并取整)
milliseconds = int((current_seconds - int(current_seconds)) * 1000)
# 拼接成包含毫秒的字符串
precise_time = f"{formatted_time}.{milliseconds:03d}"
print(precise_time)
# 可能的输出: 2025-10-27 15:30:45.123

使用 datetime 模块(推荐)

datetime 模块提供了更直观、更强大的功能,是处理日期和时间的首选。

将毫秒时间戳转换为 datetime 对象

datetime.utcfromtimestamp()datetime.fromtimestamp() 可以直接接收一个以秒为单位的浮点数,我们同样需要将毫秒除以 1000。

from datetime import datetime, timezone
# 假设我们有一个毫秒时间戳
millis_timestamp = 1678886400000
# 1. 将毫秒转换为秒
seconds_timestamp = millis_timestamp / 1000.0
# 2. 创建一个 datetime 对象
#    fromtimestamp() 创建本地时间的 datetime 对象
#    utcfromtimestamp() 创建 UTC 时间的 datetime 对象
dt_object_utc = datetime.utcfromtimestamp(seconds_timestamp)
dt_object_local = datetime.fromtimestamp(seconds_timestamp)
print(f"原始毫秒时间戳: {millis_timestamp}")
print(f"UTC datetime 对象: {dt_object_utc}")
print(f"本地 datetime 对象: {dt_object_local}")

输出:

Python中convertmillis函数如何使用?-图3
(图片来源网络,侵删)
原始毫秒时间戳: 1678886400000
UTC datetime 对象: 2025-03-15 00:00:00
本地 datetime 对象: 2025-03-15 08:00:00  # 注意:时区不同,时间会不一样

datetime 对象格式化为字符串

使用 strftime() 方法,可以非常灵活地格式化 datetime 对象。

from datetime import datetime
millis_timestamp = 1678886400000
dt_object = datetime.utcfromtimestamp(millis_timestamp / 1000.0)
# 格式化为标准字符串
formatted_str = dt_object.strftime("%Y-%m-%d %H:%M:%S")
print(f"标准格式: {formatted_str}")
# 格式化为更易读的字符串
readable_str = dt_object.strftime("%B %d, %Y at %I:%M:%S %p")
print(f"易读格式: {readable_str}")
# 获取包含毫秒的字符串
# dt_object 的 microsecond 属性包含微秒 (1秒 = 1,000,000微秒)
# 所以毫秒 = microsecond // 1000
milliseconds_str = dt_object.strftime("%Y-%m-%d %H:%M:%S") + f".{dt_object.microsecond // 1000:03d}"
print(f"精确到毫秒: {milliseconds_str}")

输出:

标准格式: 2025-03-15 00:00:00
易读格式: March 15, 2025 at 12:00:00 AM
精确到毫秒: 2025-03-15 00:00:00.000

自定义 convertmillis 函数

我们可以基于上面的知识,创建一个你想要的 convertmillis 函数,这里提供一个功能全面的版本。

from datetime import datetime, timezone
def convert_millis(millis, timezone_str='UTC', format_str="%Y-%m-%d %H:%M:%S"):
    """
    将毫秒时间戳转换为指定时区的格式化字符串。
    Args:
        millis (int): 毫秒时间戳。
        timezone_str (str): 目标时区,'UTC', 'Asia/Shanghai', 'America/New_York'。
                            默认为 'UTC'。
        format_str (str): 输出字符串的格式,默认为 "%Y-%m-%d %H:%M:%S"。
    Returns:
        str: 格式化后的时间字符串,如果转换失败,返回错误信息。
    """
    if not isinstance(millis, (int, float)):
        return "错误:输入必须是数字"
    try:
        # 1. 将毫秒转换为秒
        seconds = millis / 1000.0
        # 2. 创建一个 UTC 时间的 datetime 对象
        #    使用 fromtimestamp(..., tz=timezone.utc) 更明确地指定时区
        dt_utc = datetime.fromtimestamp(seconds, tz=timezone.utc)
        # 3. 转换为目标时区
        #    需要先安装 pytz 库: pip install pytz
        import pytz
        target_timezone = pytz.timezone(timezone_str)
        dt_target = dt_utc.astimezone(target_timezone)
        # 4. 格式化并返回字符串
        return dt_target.strftime(format_str)
    except Exception as e:
        return f"转换时发生错误: {e}"
# --- 使用示例 ---
# 示例时间戳 (2025-03-15 00:00:00 UTC)
millis_timestamp = 1678886400000
# 1. 转换为 UTC 时间
print(f"UTC时间: {convert_millis(millis_timestamp, 'UTC')}")
# 2. 转换为北京时间 (UTC+8)
print(f"北京时间: {convert_millis(millis_timestamp, 'Asia/Shanghai')}")
# 3. 转换
分享:
扫描分享到社交APP
上一篇
下一篇