You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中替换datetime.now()获取连续毫秒/微秒级时间戳的咨询

解决Python中datetime.now()生成非连续时间戳的问题

你碰到的其实是系统时钟分辨率限制导致的问题——datetime.now()的精度完全依赖操作系统的系统时钟更新频率,比如在Windows系统上,默认系统时钟的分辨率通常是10-15毫秒左右,所以你会看到时间戳每隔5毫秒(甚至更大间隔)才变化一次,没法得到连续的微秒级时间。

下面给你两种可行的解决方案,根据你的需求选择:

方案一:使用time.time_ns()获取高精度连续时间戳(推荐)

Python 3.7及以上版本提供了time.time_ns()函数,它返回从Unix纪元(1970-01-01 00:00:00 UTC)开始的纳秒数,精度远高于datetime.now(),大多数现代操作系统都能提供微秒级的连续时间输出。你可以把它转换成需要的时间戳格式:

import time
from datetime import datetime

def get_continuous_microsecond_timestamp():
    # 获取纳秒级时间戳,转成秒的浮点数
    ns_time = time.time_ns()
    # 转换成datetime对象(精确到微秒)
    dt = datetime.fromtimestamp(ns_time / 10**9)
    # 格式化为你需要的字符串格式,比如包含微秒的20位字符串
    return dt.strftime("%Y%m%d%H%M%S%f")

# 测试输出
print(get_continuous_microsecond_timestamp())
print(get_continuous_microsecond_timestamp())

这个方法的优势是直接依赖系统的高精度时钟,不需要额外逻辑处理,生成的时间戳是真实的系统时间,且连续无间隔(只要系统时钟支持微秒级更新)。

方案二:基于datetime.now()加计数器保证连续性

如果你需要保留datetime对象的使用习惯,或者在低版本Python中使用,可以通过维护一个计数器来手动保证时间戳的连续性。当两次调用的系统时间相同时,手动递增微秒部分:

from datetime import datetime
import threading

class ContinuousTimestampGenerator:
    def __init__(self):
        self.last_timestamp = datetime.now()
        # 加锁保证多线程环境下的安全性
        self._lock = threading.Lock()

    def generate_timestamp(self):
        with self._lock:
            current = datetime.now()
            # 如果当前时间不大于上次记录的时间,手动递增微秒
            if current <= self.last_timestamp:
                # 递增微秒
                next_microsecond = self.last_timestamp.microsecond + 1
                if next_microsecond >= 1000000:
                    # 微秒溢出,进位到秒
                    current = self.last_timestamp.replace(
                        second=self.last_timestamp.second + 1,
                        microsecond=0
                    )
                else:
                    current = self.last_timestamp.replace(microsecond=next_microsecond)
            self.last_timestamp = current
            # 返回格式化后的时间戳字符串
            return current.strftime("%Y%m%d%H%M%S%f")

# 使用示例
generator = ContinuousTimestampGenerator()
print(generator.generate_timestamp())
print(generator.generate_timestamp())

这个方法的好处是即使系统时钟精度不够,也能生成连续递增的时间戳,但要注意:如果调用频率极高(比如每秒超过100万次),可能会出现秒级的进位,不过这种场景非常少见。

另外补充一点:在Linux系统上,datetime.now()本身通常已经支持微秒级的连续更新,但Windows系统确实会有明显的间隔,所以上面的方案在跨平台场景下更可靠。

内容的提问来源于stack exchange,提问作者JakubM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:20:18