温馨提示×

ubuntu时间戳如何精确到毫秒

小樊
38
2026-09-28 09:42:52
栏目: 智能运维

在 Ubuntu(Linux)里,时间戳本身就可以精确到毫秒,只是不同的命令/语言默认显示的精度不同。下面按常见场景说明。


一、命令行获取毫秒级时间戳

1. date 命令(最常用)

date +%s%3N
  • %s:秒级 Unix 时间戳
  • %3N:毫秒(3 位)

示例输出:

1718612345678

如果只要毫秒部分:

date +%3N

2. 更高精度(微秒 / 纳秒)

date +%s%6N   # 微秒
date +%s%9N   # 纳秒

二、Shell 脚本中获取毫秒时间

now=$(date +%s%3N)
echo "当前毫秒时间戳: $now"

三、编程语言中获取毫秒时间戳

1. Python

import time
print(int(time.time() * 1000))

或(更精确):

import time
print(time.time_ns() // 1_000_000)

2. C / C++

#include <stdio.h>
#include <time.h>

int main() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    long ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
    printf("%ld\n", ms);
    return 0;
}

3. Java

System.currentTimeMillis();

4. Node.js

Date.now();

四、将毫秒时间戳转成可读时间

date -d @1718612345.678

或:

echo 1718612345678 | awk '{print strftime("%Y-%m-%d %H:%M:%S", $1/1000)}'

五、常见误区

  • ❌ “Unix 时间戳只有秒”
    • 实际是 秒 + 小数(毫秒/微秒/纳秒)
  • ❌ date +%s 永远只有秒
    • 加 %N 就能扩展精度

如果你有具体使用场景(日志、性能统计、数据库、脚本同步等),我可以给你更合适的方案。

0 踩