Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

4 Answers

up vote 12 down vote accepted

In 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

share|improve this answer
2  
Great little tip. BTW, if you do it the other way around, that is: "file_20090601_172215", you will see the files in the correct order in an alphabetic list. –  TonJ Jun 1 '09 at 13:00
    
Yeah - that's a good tip too! –  aalaap Jun 1 '09 at 13:12
2  
You can also use %time::=% to remove the colons. –  grawity Jun 1 '09 at 13:33
2  
I'd say that date substring-ing would break as soon as the system locale differs from when the script was tested? It could even work for the testing user and break as the script runner because of different date display formats set... –  Oskar Duveborn Jun 1 '09 at 18:17
1  
Beware hours 0 - 9! CMD sets the first character of the hour to <SPACE>, rather than 0. The COPY command above is going to have problems if you don't enclose the destination filename in quotes. –  Evan Anderson Jun 1 '09 at 20:09
show 3 more comments

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
share|improve this answer
    
wow, never know about the :x=y trick. that's really cool. –  Eugene Katz Jun 1 '09 at 21:37
add comment

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
share|improve this answer
add comment

I know the question wasn't about Unix, but for completeness, here's how to do it in bash:

% cp somefile.txt somefile-$(date +%Y%m%d-%H%M).txt
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.