0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

コマンドプロンプトでタイムスタンプを付ける

Posted at

ユースケース

Python等で作成した.exeコマンドラインソフトウェアに対して、非ITエンジニアが利用すると想定してバッチファイルでインターフェースを作ります。(入力ファイルをドラッグアンドドロップすれば動くようになる)

このバッチファイルと.exeを通じてさらにファイル出力をする際に、タイムスタンプが必要です。タイムスタンプをコマンドプロンプト上で取得する方法を以下で書いていきます。

登場するコマンド

以下、コマンドプロンプトの事例を記載します。

コマンド 説明
time 時刻を取得
date 日付を取得

コマンド

>For /f "tokens=1-3 delims=/ " %a in ('date /t') do (set mydate=%a-%b-%c)
>(set mydate=2024-07-21 )
>For /f "tokens=1-2 delims=:" %a in ('time /t') do (set mytime=%a-%b)
>(set mytime=16-29 )
>echo %mydate%_%mytime%
2024-07-21_16-29

説明

コマンドプロンプトのfor文にて、/f オプションを使って文字列のフォーマットが可能です。tokensで取得する文字列のインデックスを指定します。delimsで文字列を分割する文字を指定します。2024/07/21であれば/をdelimsに指定することで、文字列2024, 07, 21を受け取ります。for文なので、do ()で変数に代入すればタイムスタンプの変数を保持することができます。

for文の %a ですが、開始するアルファベットを明示する意味があります。for directiveは勝手にアルファベット順に変数をマップします。上記のコマンドの例だと、%aで開始して、%b%cが勝手に使われています。

なお、バッチファイルに記入する際はfor文のローカルパラメータ %aなどにもう一つパーセントを付けて%%aなどとします。

参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?