在 CentOS 系统中,时间戳通常用于表示某个特定时间点距离 1970 年 1 月 1 日(Unix 纪元)的秒数,在许多场景中都非常有用,例如文件操作、日志记录和系统任务调度等。以下是 CentOS 中时间戳配置的详细步骤:
获取当前时间戳
-
使用
date命令:- 获取当前时间的 Unix 时间戳(以秒为单位):
date +%s - 获取当前时间的毫秒级时间戳:
date +%s%3N或者使用
date +%s%N获取纳秒级时间戳,但需要注意这个值可能会超出 32 位整数的范围。
- 获取当前时间的 Unix 时间戳(以秒为单位):
-
使用 Python 脚本(如果系统中安装了 Python):
- 获取当前时间的时间戳(秒级):
python -c 'import time; print(int(time.time()))' - 获取当前时间的毫秒级时间戳:
python -c 'import time; print(int(time.time() * 1000))'
- 获取当前时间的时间戳(秒级):
-
使用 Perl 脚本(如果系统上安装了 Perl):
- 获取当前时间的 Unix 时间戳(以秒为单位,精确到微秒):
perl -MTime::HiRes -e 'printf("%d
- 获取当前时间的 Unix 时间戳(以秒为单位,精确到微秒):
", Time::HiRes::time())’
```
- 获取当前时间的毫秒级时间戳:
perl -MTime::HiRes -e 'printf("%d
", Time::HiRes::time() * 1000)’
```
设置系统时间
-
使用
timedatectl命令(推荐):- 查看当前时间设置:
timedatectl status - 设置系统时间为本地时间:
sudo timedatectl set-local-rtc 1 --adjust-system-clock - 设置系统时间为 UTC 时间:
sudo timedatectl set-local-rtc 0 --adjust-system-clock - 手动设置系统时间:
sudo timedatectl set-time 'YYYY-MM-DD HH:MM:SS'例如:
sudo timedatectl set-time '2023-04-01 12:34:56' - 同步系统时间到硬件时钟:
sudo hwclock --systohc或者使用
timedatectl:sudo timedatectl set-local-rtc 1
- 查看当前时间设置:
-
使用
date命令(临时设置):- 临时设置系统时间:
sudo date -s 'YYYY-MM-DD HH:MM:SS'例如:
sudo date -s '2023-04-01 12:34:56' - 同步系统时间到硬件时钟:
sudo hwclock --systohc
- 临时设置系统时间:
同步系统时间
-
使用 NTP 服务:
- 安装 NTP 服务:
sudo yum install ntp - 启动并启用 NTP 服务:
sudo systemctl start ntpd sudo systemctl enable ntpd - 检查 NTP 服务状态:
sudo systemctl status ntpd - 同步时间:
sudo ntpdate pool.ntp.org
- 安装 NTP 服务:
-
使用 chrony 服务(CentOS 7 及以上版本):
- 安装 chrony 服务:
sudo yum install chrony - 启动并启用 chrony 服务:
sudo systemctl start chronyd sudo systemctl enable chronyd - 检查 chrony 服务状态:
sudo systemctl status chronyd - 同步时间:
sudo chronyc sources sudo chronyc tracking
- 安装 chrony 服务:
以上步骤涵盖了在 CentOS 系统中获取、设置和同步时间戳的基本操作。根据具体需求,可以选择适合的方法进行操作。