Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a file name as a timestamp in a batch job

We have a batch job that runs every day and copies a file to a pickup folder. I want to also take a copy of that file and drop it into an archive folder with the filename

 yyyy-MM-dd.log 

What's the easiest way to do this in a Windows batch job?

I'm basically looking for an equivalent of this Unix command:

cp source.log `date +%F`.log 
like image 721
Eoin Campbell Avatar asked Jun 30 '09 16:06

Eoin Campbell


People also ask

How do I create a timestamp in a batch file?

to create a log file (yyyymmdd-hhmmss-nn. log) with date and timestamps to within 1/100 second. Then, the batch file parses the first line of the output file. (The first For/f command could instead use Date/T, but the second can't use Time/T because Time/T displays time in a 12-hour clock format.)

How do you insert date and time in FileName?

I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.

How do I create a batch file title?

Remarks. To create window title for batch programs, include the title command at the beginning of a batch program. After a window title is set, you can reset it only by using the title command.


2 Answers

CP source.log %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.log 

But it's locale dependent. I'm not sure if %DATE% is localized, or depends on the format specified for the short date in Windows.

Here is a locale-independent way to extract the current date from this answer, but it depends on WMIC and FOR /F:

FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO @SET B=%%A CP source.log %B:~0,4%-%B:~4,2%-%B:~6,2%.log 
like image 65
opello Avatar answered Oct 24 '22 17:10

opello


This worked for me and was a filename-safe solution (though it generates a MM-dd-YYYY format):

C:\ set SAVESTAMP=%DATE:/=-%@%TIME::=-% C:\ set SAVESTAMP=%SAVESTAMP: =% C:\ set SAVESTAMP=%SAVESTAMP:,=.%.jpg C:\ echo %SAVESTAMP% [email protected] 

The first command takes a DATE and replaces / with -, takes the TIME and replaces : with -, and combines them into DATE@TIME format. The second set statement removes any spaces, and the third set replaces , with . and appends the .jpg extension.

The above code is used in a little script that pulls images from a security IP Camera for further processing:

:while set SAVESTAMP=%DATE:/=-%@%TIME::=-% set SAVESTAMP=%SAVESTAMP: =% set SAVESTAMP=%SAVESTAMP:,=.%.jpg wget-1.10.2.exe --tries=0 -O %SAVESTAMP% http://admin:<password>@<ip address>:<port>/snapshot.cgi timeout 1 GOTO while 
like image 21
Daniel Sokolowski Avatar answered Oct 24 '22 19:10

Daniel Sokolowski