3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルの日付&日時機能のメモ(dateコマンド不要)

Posted at

はじめ

シェルの日時機能の雑なメモです。意外と知られていない気がしますが、bash、ksh、zshを使うのであれば日時の処理に date コマンドは必要なかったりします。シェルの機能なので date コマンドを使うよりも速いです。

現在日時の取得

$ bash -c 'printf "%(%F %T)T\n"'
2025-03-09 17:47:05

$ ksh -c 'printf "%(%F %T)T\n"'
2025-03-09 17:48:12

$ zsh -c 'zmodload zsh/datetime; strftime "%F %T"'
2025-03-09 17:50:36

UNIXタイムの取得(+ マイクロ秒 or ナノ秒)

$ bash -c 'echo $EPOCHSECONDS; echo $EPOCHREALTIME'
1741510387
1741510387.048045

$ bash -c 'printf "%(%s)T\n"'
1741510525

$ sh -c 'zmodload zsh/datetime; echo $EPOCHSECONDS; echo $EPOCHREALTIME'
1741510368
1741510368.5248692036

$ ksh -c 'printf "%(%s.%N)T\n"'
1741489522.461796790

$ mksh -c 'echo $EPOCHREALTIME'
1741489529.610125

UNIXタイムからの変換

$ bash -c 'printf "%(%F %T)T\n" 1000000000'
2001-09-09 10:46:40

$ ksh -c 'printf "%(%F %T)T\n" "#1000000000"'
2001-09-09 10:46:40

$ zsh -c 'zmodload zsh/datetime; strftime "%F %T" 1000000000'
2001-09-09 10:46:40

相対時間の計算

$ ksh -c 'printf "%(%F %T)T\n" "now + 1day"'
2025-03-10 17:58:55

おまけ: 日時を変数にいれる方法

$ bash -c 'printf -v now "%(%F %T)T"; echo $now'
2025-03-09 18:02:00

サブシェルを使う now=$(printf "%(%F %T)T" よりも -v オプションを使ったほうが速いです。

さいごに

そのうち忘れる予定なので現在覚えていることのメモ。他にも思い出したら or 調べて気づいたら追記します。

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?