插件窝 干货文章 linux系统时间怎么获取

linux系统时间怎么获取

时间 bash time 系统 397    来源:    2025-04-06

在 Linux 系统中,获取系统时间有多种方式,以下是常用的方法:


1. 使用 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


2. 使用 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

3. 通过 /proc 虚拟文件系统

获取系统启动后的运行时间(单位:秒):

cat /proc/uptime

输出示例:

12345.67 98765.43  # 第一个值为系统运行时间,第二个值为空闲时间。

4. 使用 hwclock 命令

查看硬件时钟(RTC)时间:

sudo hwclock --show

注意: 需要 root 权限。


5. 编程语言获取时间

  • 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"
    

6. 高精度时间获取

  • clock_gettime(纳秒级精度,需编程调用):

    #include <time.h>
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);  // 获取系统时间
    
  • /proc/timer_list(内核级时间信息,需 root):

    sudo cat /proc/timer_list
    

常见问题解决

  1. 时间不一致

    • 同步网络时间(NTP): bash sudo timedatectl set-ntp true
    • 手动同步: bash sudo ntpdate pool.ntp.org
  2. 时区设置

    sudo timedatectl set-timezone Asia/Shanghai
    

根据需求选择合适的方法。普通用户推荐 datetimedatectl,开发者可根据场景选择编程接口或高精度工具。