温馨提示×

centos怎样获取时间戳

小樊
48
2026-09-11 16:12:58
栏目: 智能运维

在 CentOS(或其他 Linux 系统)中,获取时间戳(通常指 Unix 时间戳,即从 1970-01-01 00:00:00 UTC 到现在的秒数)有多种方式:


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

当前时间戳(秒级)

date +%s

当前时间戳(毫秒级)

date +%s%3N

纳秒级时间戳

date +%s%N

2. 获取指定时间的时间戳

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

3. 使用 printf(bash 内建,不依赖外部命令)

printf "%(%s)T\n"

4. 使用 Python(如果已安装)

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

5. 使用 Perl

perl -e 'print time(), "\n"'

示例输出

$ date +%s
1719300000

如果你是要在 Shell 脚本中使用时间戳,通常这样写:

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

需要我说明 时间戳转日期时区相关的问题 也可以继续问。

0