I have scheduled backup script that makes the database dump. How can I add the date timestamp to the file name?
I am talking about Windows and CMD.
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.
Sign up to join this communityIn the command prompt and batch files, you can use %date%
and %time%
to return the date and time respectively. Date works fine, but the time value returned contains colons, which are illegal for use in filenames, but there is a way to remove those.
Use something like:
COPY file.txt file_%time:~0,2%%time:~3,2%%time:~6,2%_%date:~-10,2%%date:~-7,2%%date:~-4,4%.txt
This will produce a filename such as file_172215_01062009.txt
Update: The comments below have interesting twists on this command as well as some potential problems you can avoid.
%DATE%
and %TIME%
are locale-aware! It means that on a European machine, you get DD.MM.YYYY
. Arrgh.
Use the %DATE%
and/or %TIME
environment variables, optionally substituting the characters that are not allowed in filenames, using %name:from=to%
(%TIME::=%
would remove all colons).
theory » echo %date% 2009-06-01 theory » echo %time% 16:30:41,46 theory » echo %time::=% 163052,17 theory » echo %time::=,% 16,30,58,68 theory » echo backup-%date%-%time::=-%.zip backup-2009-06-01-16-31-18,82.zip
set tmp=%tmp:x=y%
etc.
The only reliable way to get appropriate date whatever regional setting are, is the solution from foxidrive @ https://stackoverflow.com/questions/11037831/filename-timestamp-in-windows-cmd-batch-script
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Use %DATE% variable in the filename.
There is a %TIME% variable as well, but it contains characters not allowed in a file name.
Here is an example of writing a line of text into a new file, where the file created has a date and time in its name.
echo "testfile" >> backup-%DATE%.txt
Use the %date%
and %time%
variables, and you can use For /f
command to parse the tokens delimited by /
or locale-specific format to change formats.