1

Windows batch,
How to rename a directory to date and time with seconds

Current drive and directory is S:\1 = a backup.

via batch, How to automate, How to rename a directory, not a file?
something like -- Rename S:\1 S:\20171022_131459

2017 year
10 October
22 day
13 hours
14 minutes
59 seconds

Below was does at the command line with one %
on a file named hope.txt, not a directory

ren hope.txt 20171022.txt

.

for /f "tokens=1-4 delims=- " %d in ("%date%") do rename "hope.txt" %d%e%f.txt

and in part 2 (time)
Seconds are missing in name and
it is not a directory, but, it does a file
named hope.txt with hours and minutes.

rename "hope.txt" 1314.txt 

.

for /f "tokens=1-2 delims=: " %G in ("%time%") do rename "hope.txt" %G%H.txt

--

2
  • 2
    Depending on your Windows version, you may not be able to rename a directory with ren: you may need to use move instead.
    – AFH
    Commented Oct 22, 2017 at 23:18
  • On Windows 10/11 you can simply rename a directory: ren old new. Otherwise use move old new. If you need to know how to format date and time I'd suggest to do it as described in this answer.
    – Andreas
    Commented Nov 8, 2023 at 6:17

2 Answers 2

0

Below is one answer to renaming a directory
From C:\99
To _ C:\YearMMDD_hhMMssFF
(Year Month Day _ hours Minutes seconds Fraction of 1 second)

C:\99 might be the name of a file
C:\99 might be the name of a directory

On Windows XP 32 bit, ren works.
(ren = rename Directory or File)

On this one computer we have 3 delimiters of - : .

Date time format of:
Date ______ time
2017-10-23 19:28:13.01
a___ b__c__d__e__f__g

Answer, cmd line:

for /f "tokens=1-7 delims=-:. " %a in ("%date% %time%") do ren c:\99 %a%b%c_%d%e%f%g  

Directory C:\99
Directory C:\20171023_19473074

.

Answer, batch file with double %%:

for /f "tokens=1-7 delims=-:. " %%a in ("%date% %time%") do ren c:\99 %%a%%b%%c_%%d%%e%%f%%g  

Directory C:\99
Directory C:\20171023_19480420

--

2
  • why do you use XP in 2017?
    – phuclv
    Commented Jul 10, 2023 at 3:47
  • %date% and %time% are both locale dependent, so using them is a very bad idea
    – phuclv
    Commented Jul 10 at 11:30
-1

I think this does what you are looking for:

for /f "tokens=2-7 delims=/:. " %a in ("%date% %time%") do ren dir1 %c%ab%b_%d%e%f

The output looks like this:

ren dir1 201710b22_201108

In a batch file you need extra % so this line becomes:

for /f "tokens=2-7 delims=/:. " %%a in ("%date% %time%") do ren dir1 %%c%%ab%%b_%%d%%e%%f
3
  • %date% and %time% are both locale dependent, so using them is a very bad idea
    – phuclv
    Commented Jul 10, 2023 at 3:47
  • Thats All well and good except my code allowed for that.
    – uSlackr
    Commented Jul 31, 2023 at 20:44
  • who said that the OPs and readers of this also use the same locale as you?
    – phuclv
    Commented Aug 1, 2023 at 4:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .