温馨提示×

怎样获取ubuntu时间戳

小樊
56
2026-09-04 02:57:20
栏目: 智能运维

在 Ubuntu(Linux)系统中,获取“时间戳”通常指获取 Unix 时间戳(从 1970-01-01 00:00:00 UTC 到现在的秒数或毫秒数)。下面按常见场景说明。


一、获取当前 Unix 时间戳(秒级)

1. 使用 date 命令(最常用)

date +%s

示例输出:

1719301234

二、获取毫秒级时间戳

方法 1:date(较新版本支持)

date +%s%3N

方法 2:使用 python

python3 -c 'import time; print(int(time.time()*1000))'

三、获取指定时间的时间戳

将某个时间转为时间戳

date -d "2024-06-25 12:00:00" +%s

将可读时间字符串转为时间戳

date -d "next monday" +%s

四、在脚本中使用时间戳

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

五、在编程语言中获取(补充)

Python

import time
print(time.time())        # 秒(浮点)
print(int(time.time()))   # 秒(整数)

Shell + awk

awk 'BEGIN {print systime()}'

六、注意事项

  • date +%s 返回的是 UTC 时间戳,不受时区影响
  • 毫秒/微秒精度依赖系统时钟和命令版本

如果你是想:

  • 获取文件时间戳
  • 获取启动时间 / 运行时间
  • 在 Docker / WSL 中获取

可以告诉我具体场景,我可以给你更精准的方法。

0 踩