ubuntu

如何用Ubuntu命令行获取时间戳

小樊
54
2025-05-09 19:12:30
栏目: 智能运维

在 Ubuntu 命令行中,你可以使用多种方法来获取当前的时间戳。以下是几种常用的方法:

  1. 使用 date 命令

    • 获取 Unix 时间戳(秒级)

      date +%s
      
    • 获取 Unix 时间戳(毫秒级)

      date +%s%3N
      

      或者

      date +%s | xargs -I {} echo "{}$(printf '%03d' $(date +%N | cut -b1-3))"
      
  2. 使用 perl 命令

    • 获取 Unix 时间戳(秒级)

      perl -MTime::HiRes -e 'print time, "\n"'
      
    • 获取 Unix 时间戳(毫秒级)

      perl -MTime::HiRes -e 'printf "%.0f\n", Time::HiRes::time() * 1000'
      
  3. 使用 python 命令

    • 获取 Unix 时间戳(秒级)

      python3 -c 'import time; print(int(time.time()))'
      
    • 获取 Unix 时间戳(毫秒级)

      python3 -c 'import time; print(int(time.time() * 1000))'
      
  4. 使用 awk 命令

    • 获取 Unix 时间戳(秒级)

      awk 'BEGIN {print systime()}'
      
    • 获取 Unix 时间戳(毫秒级)

      awk 'BEGIN {printf "%.0f\n", systime() * 1000}'
      

示例

假设你想获取当前的 Unix 时间戳(秒级),可以使用以下命令之一:

date +%s

或者

perl -MTime::HiRes -e 'print time, "\n"'

这些命令都会输出类似于 1697054400 的数字,表示自 1970-01-01 00:00:00 UTC 以来的秒数。

注意事项

希望这些方法能帮助你在 Ubuntu 命令行中顺利获取所需的时间戳!

0
看了该问题的人还看了