温馨提示×

如何获取Ubuntu时间戳

小樊
50
2026-08-11 23:16:47
栏目: 智能运维

在 Ubuntu(以及大多数 Linux 系统)中,获取**时间戳(Timestamp)**通常指获取 Unix 时间戳(自 1970-01-01 00:00:00 UTC 起的秒数)。下面按常见需求给你几种方法。


一、获取当前 Unix 时间戳(最常用)

✅ 方法 1:date 命令

date +%s

输出示例:

1700000000

二、获取当前时间戳(纳秒级)

date +%s%N

输出示例:

1700000000123456789

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

1️⃣ 指定日期时间

date -d "2024-01-01 12:00:00" +%s

2️⃣ 指定日期(默认 00:00:00)

date -d "2024-01-01" +%s

四、获取高精度时间戳(推荐)

date + 纳秒

date +%s.%N

示例:

1700000000.123456789

五、使用 Python 获取时间戳(更灵活)

秒级

python3 -c "import time; print(int(time.time()))"

毫秒级

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

纳秒级

python3 -c "import time; print(time.time_ns())"

六、获取文件的时间戳

修改时间(mtime)

stat -c %Y filename

访问时间(atime)

stat -c %X filename

状态变更时间(ctime)

stat -c %Z filename

七、查看当前系统时间(非时间戳)

date

八、常见时间戳单位对照

单位 示例
1700000000
毫秒 1700000000000
微秒 1700000000000000
纳秒 1700000000000000000

九、常见用途示例

用于脚本

start_time=$(date +%s)
# do something
end_time=$(date +%s)
echo "耗时: $((end_time - start_time)) 秒"

如果你有具体场景(比如:日志、脚本、数据库、C/C++、Docker、定时任务),可以告诉我,我可以给你更贴近实战的示例。

0