Archive for October, 2008

Parsing date / time in windows shell for log file timestamp

October 6, 2008

Quick post to share a simple solution I came up with to a problem I encountered this morning. A script I inherited needed to be tweaked so that in an error condition the log file is copied to an auditing location. Currently the filename of the log file is static, so this location would be overwritten each time the error condition occurs. Below is a simple solution to reference a filename with a timestamp for these kinds of issues.

It only has resolution to the minute, this is adequate for my needs. To get resolution to seconds or milliseconds you could pipe a CRLF to the ‘time’ command and redirect output to a text file. Then parse the text file instead of the time command directly.
FOR /f "usebackq tokens=2-4 delims=/ " %A in (`date /t`) do (

REM: Note: converting hours to military time
FOR /f "usebackq tokens=1-3 delims=: " %A in (`time /t`) do (
if "%C" equ "PM" (SET /A _NOW_HOUR = %_NOW_HOUR% + 12))


REM Reference the timestamp as follows:
copy MyLogFile.txt \\server\share\MyLogFile_%_NOW_DATETIME%.TXT

EDIT: ok, I have already come to a better solution 🙂

for /F "tokens=1,2,3,4,5,6,7* delims=.:^/^ " %i in ("%date%.%time%") do (
SET _Timestamp=%l%j%k%m%n%o
REM pad hour if single digit
if "%m" neq "" if %m LSS 10 SET _Timestamp=%l%j%k0%m%n%o)