温馨提示×

ubuntu时间戳怎样比对

小樊
53
2026-10-01 07:35:09
栏目: 智能运维

在 Ubuntu(Linux)里,“时间戳”通常指 Unix 时间戳(从 1970-01-01 00:00:00 UTC 起的秒数,或毫秒数)。常见比对方式如下:


一、在命令行里比对时间戳

1. 两个时间戳直接比较(数字比较)

Unix 时间戳本质是数字,可以直接比大小:

ts1=1710000000
ts2=1710003600

if [ "$ts1" -lt "$ts2" ]; then
    echo "ts1 早于 ts2"
else
    echo "ts1 晚于或等于 ts2"
fi

2. 当前时间戳 vs 某个时间戳

now=$(date +%s)
target=1710000000

if [ "$now" -gt "$target" ]; then
    echo "当前时间已超过目标时间"
fi

3. 时间戳转成可读时间再比对

date -d @1710000000
date -d @1710003600

二、在脚本中计算时间差

ts1=1710000000
ts2=1710003600
diff=$((ts2 - ts1))

echo "相差 ${diff} 秒"

三、文件时间戳比对(常见场景)

1. 比较两个文件的修改时间

if [ file1 -nt file2 ]; then
    echo "file1 更新"
fi

if [ file1 -ot file2 ]; then
    echo "file1 更旧"
fi

2. 获取文件时间戳

stat -c %Y file1   # 修改时间(秒)
stat -c %Y file2

四、毫秒 / 微秒时间戳

date +%s%3N   # 毫秒
date +%s%6N   # 微秒

比对时注意单位一致。


五、用 Python 比对(更灵活)

python3 -c "
import time
t1=1710000000
t2=time.time()
print(t2 > t1)
"

如果你能说明 具体场景(比如:日志时间、文件时间、数据库时间、Shell/Python 脚本),我可以给你更精确的示例。

0 踩