在 Linux 系统中,获取系统时间有多种方式,以下是常用的方法:
date
命令最简单直接的方式,显示当前系统时间和日期:
date
输出示例:
Wed Jun 12 15:30:45 CST 2024
常用选项:
- 格式化输出(例如 YYYY-MM-DD HH:MM:SS
):
bash
date "+%Y-%m-%d %H:%M:%S"
- 获取时间戳(秒级):
bash
date +%s
- 获取毫秒级时间戳:
bash
date +%s%3N
timedatectl
命令查看系统时间和时区配置(适用于 systemd 系统):
timedatectl
输出示例:
Local time: Wed 2024-06-12 15:30:45 CST
Universal time: Wed 2024-06-12 07:30:45 UTC
RTC time: Wed 2024-06-12 07:30:45
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
NTP service: active
RTC in local TZ: no
/proc
虚拟文件系统获取系统启动后的运行时间(单位:秒):
cat /proc/uptime
输出示例:
12345.67 98765.43 # 第一个值为系统运行时间,第二个值为空闲时间。
hwclock
命令查看硬件时钟(RTC)时间:
sudo hwclock --show
注意: 需要 root 权限。
Python:
import time
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 格式化时间
print(time.time()) # 时间戳
Bash 脚本:
#!/bin/bash
current_time=$(date "+%Y-%m-%d %H:%M:%S")
echo "Current time: $current_time"
clock_gettime
(纳秒级精度,需编程调用):
#include <time.h>
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts); // 获取系统时间
/proc/timer_list
(内核级时间信息,需 root):
sudo cat /proc/timer_list
时间不一致:
bash
sudo timedatectl set-ntp true
bash
sudo ntpdate pool.ntp.org
时区设置:
sudo timedatectl set-timezone Asia/Shanghai
根据需求选择合适的方法。普通用户推荐 date
或 timedatectl
,开发者可根据场景选择编程接口或高精度工具。