How to Pad Leading Zeros for %time% Variable in Windows Batch Scripts for Consistent File Naming


1 views


When working with batch scripts that incorporate timestamps into filenames, many Windows programmers encounter formatting inconsistencies. The built-in %time% environment variable returns time in the format H:MM:SS.mm, which creates an unwanted space before single-digit hours (e.g., " 9:23:17.88" instead of "09:23:17.88"). This leads to improperly formatted filenames and potential file sorting issues.

Consider this common file naming pattern:

set logfile=C:\Temp\robolog_%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log

With the space before single-digit hours, you might get robolog_20230815_ 93208.log instead of the desired robolog_20230815_093208.log.

Here are three effective approaches to handle this:

:: Method 1: Simple string replacement
set hour=%time:~0,2%
set hour=%hour: =0%
set logfile=C:\Temp\robolog_%date:~-4%%date:~4,2%%date:~7,2%_%hour%%time:~3,2%%time:~6,2%.log
:: Method 2: Conditional padding
set hour=%time:~0,2%
if %hour% LSS 10 (set hour=0%hour:~1%) else (set hour=%hour%)
set logfile=C:\Temp\robolog_%date:~-4%%date:~4,2%%date:~7,2%_%hour%%time:~3,2%%time:~6,2%.log
:: Method 3: Full timestamp function
:GetTimestamp
setlocal
set hour=%time:~0,2%
set hour=%hour: =0%
set min=%time:~3,2%
set sec=%time:~6,2%
endlocal & set timestamp=%hour%%min%%sec%
goto :eof

:: Usage:
call :GetTimestamp
set logfile=C:\Temp\robolog_%date:~-4,4%%date:~4,2%%date:~7,2%_%timestamp%.log

For more complex scenarios:

  • Use WMIC for consistent formatting: wmic os get localdatetime returns YYYYMMDDHHMMSS format
  • Consider PowerShell integration for more precise datetime handling
  • Be aware of regional settings affecting %date% format

Here's a complete script that handles all edge cases:

@echo off
setlocal enabledelayedexpansion

:: Get consistent timestamp
set hour=%time:~0,2%
set hour=%hour: =0%
set min=%time:~3,2%
set sec=%time:~6,2%
set cdate=%date:~-4,4%%date:~4,2%%date:~7,2%
set timestamp=%cdate%_%hour%%min%%sec%

:: Create log file
set logfile=C:\Temp\robolog_%timestamp%.log
echo Script started at %time% > "%logfile%"

:: Main script operations here
echo Performing operations... >> "%logfile%"

endlocal

When working with timestamps in Windows batch scripts, many developers encounter this frustrating behavior:

REM Sample output from %time%
echo %time%
 9:29:17.88

Notice the unwanted space before single-digit hours? This causes issues when using timestamps in filenames.

Consider this common filename pattern:

set logfile=C:\Temp\robolog_%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log

Without proper formatting, you get inconsistent results:

  • 9:23 AM → "robolog_20230602_ 92308.log" (note the space)
  • 10:23 AM → "robolog_20230602_102308.log" (correct format)

Here's a robust approach that handles all edge cases:

@echo off
setlocal enabledelayedexpansion

:: Get raw time components
set rawtime=%time%
set hour=%rawtime:~0,2%
set minute=%rawtime:~3,2%
set second=%rawtime:~6,2%

:: Remove leading spaces from hour
set hour=%hour: =%

:: Add leading zero if needed
if %hour% LSS 10 set hour=0%hour%

:: Construct final timestamp
set timestamp=%hour%%minute%%second%

:: Example usage
set logfile=C:\Temp\robolog_%date:~-4%%date:~4,2%%date:~7,2%_%timestamp%.log
echo File will be saved as: %logfile%

For simpler cases, you can use this compact version:

for /f "tokens=1-3 delims=:." %%a in ("%time%") do set timestamp=0%%a& set timestamp=!timestamp:~-2!%%b%%c

To verify the formatting works in all scenarios:

:: Test various times
set test_times=("00:00:00.00" " 9:15:30.45" "23:59:59.99")

for %%t in %test_times% do (
    set test_time=%%t
    for /f "tokens=1-3 delims=:." %%a in ("!test_time!") do (
        set hh=0%%a
        set hh=!hh:~-2!
        set mm=%%b
        set ss=%%c
        echo Input: %%t → Output: !hh!!mm!!ss!
    )
)
  • Always use setlocal enabledelayedexpansion when working with string manipulation
  • Consider wrapping time formatting in a subroutine or include file for reusability
  • For critical systems, add validation to ensure the timestamp format is correct