Mostly Linux & Python syntax notes and hyperlinks.

Wednesday, September 25, 2024

Windows Batch Script Time Stamp - beware the morning space

I had been creating a time stamp just to give my output unique file names so as not to overwrite previous test output.

I'd been doing this:

REM TT= time tag for this run
set T=%time%
set TT=%T:~0,2%%T:~3,2%%T:~6,2%

It works fine after 10 am:

C:\Users\mharrison>set TT=%T:~0,2%%T:~3,2%%T:~6,2%
C:\Users\mharrison>echo %TT%
100359
C:\Users\mharrison>echo filename%TT%
filename100359

I've been using this time stamp method for weeks, but apparently never before 10 am. It broke my code this morning. Before 10am, the plain old time inserts a space:

C:\Users\mharrison>echo %time%
 9:56:08.38

So when I try to append it to make a unique file name, I insert a space in the file name, which confuses the code:

C:\Users\mharrison>set TT=%T:~0,2%%T:~3,2%%T:~6,2%
C:\Users\mharrison>echo %TT%
 95740
C:\Users\mharrison>echo filename%TT%
filename 95740

So I changed the method to only use the 2nd digit of the hour:

REM TT= time tag for this run
set T=%time%
set TT=%T:~1,1%%T:~3,2%%T:~6,2%


Testing in the Command Prompt window after 10am: 
C:\Users\mharrison>set T=%time%
C:\Users\mharrison>echo %T%
10:11:54.96 
C:\Users\mharrison>set TT=%T:~1,1%%T:~3,2%%T:~6,2%%T:~1,1%%T:~3,2%%T:~6,2%
C:\Users\mharrison>echo %TT%
0115401154
C:\Users\mharrison>echo filename%TT%
filename0115401154