ユースケース
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
などとします。