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

PHP如何获取与Python time.time()一致的6位小数精度时间戳

PHP获取6位小数精度时间戳的实现方法

问题背景

  • Python中time.time()返回的时间戳精度可达6位小数,样例输出:1632816181.314063
  • PHP默认直接输出microtime(true)仅能得到4位小数的时间戳,样例输出:1632816181.3140

实现方案

实际上microtime(true)本身就包含了6位的微秒精度,只是PHP默认的浮点数输出规则会自动截断小数位,你可以通过以下两种方式拿到符合要求的6位精度时间戳:

方案1:直接格式化输出(最简方案)

使用number_format指定保留6位小数即可,注意关闭千位分隔符避免格式异常:

// 直接输出6位精度时间戳
echo number_format(microtime(true), 6, '.', '');

// 如需转为浮点数存储
$timestamp = (float)number_format(microtime(true), 6, '.', '');

方案2:拆分microtime原始字符串拼接

如果你需要更稳定的精度控制,避免不同PHP版本浮点数配置差异的影响,可以拆分microtime()返回的原始字符串进行拼接:

function get_high_precision_timestamp(): float
{
    list($micro_part, $second_part) = explode(' ', microtime());
    return (float)$second_part + (float)$micro_part;
}

// 测试输出
echo number_format(get_high_precision_timestamp(), 6, '.', '');

两种方案最终都可以输出和Pythontime.time()格式完全一致的6位小数精度时间戳。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:36:04