温馨提示×

怎样处理ubuntu时间戳

小樊
42
2026-10-24 19:47:16
栏目: 智能运维

在 Ubuntu(Linux)里,“时间戳”通常指 Unix 时间戳(自 1970-01-01 00:00:00 UTC 起的秒数)。下面按常见场景给你讲怎么处理。


一、查看当前时间戳

1. 当前秒级时间戳

date +%s

2. 当前毫秒级时间戳

date +%s%3N

3. 当前微秒级时间戳

date +%s%6N

二、时间戳 → 可读时间

1. 秒级时间戳转日期

date -d @1700000000

2. 指定格式输出

date -d @1700000000 "+%Y-%m-%d %H:%M:%S"

3. UTC 时间

date -u -d @1700000000

三、日期 → 时间戳

1. 指定时间转时间戳

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

2. 当前时间转时间戳(等价 date +%s)

date +%s

四、文件时间戳处理

1. 查看文件时间

stat file.txt

2. 修改文件时间(atime / mtime)

touch -d "2025-01-01 12:00:00" file.txt

3. 按时间戳设置

touch -d @1700000000 file.txt

五、脚本中常见用法

Bash 变量

now=$(date +%s)
echo $now

计算时间差

start=$(date +%s)
sleep 2
end=$(date +%s)
echo "耗时: $((end - start)) 秒"

六、时区相关注意

Ubuntu 默认使用系统时区:

timedatectl

UTC 转本地时间:

date -d @1700000000

本地时间转 UTC 时间戳:

TZ=UTC date -d "2025-01-01 12:00:00" +%s

如果你有更具体的需求,比如:

  • 日志里的时间戳解析
  • Python / Shell 处理
  • 数据库时间戳
  • 容器 / 服务器时间不同步

可以直接说,我可以给你针对性方案。

0 踩