How to add date and time to file name in DOS?

I want to add the date and time to the file name, and then I want to move this file to the folder next to it.

Here I use the following commands to record the date and time:

set dt=%date:~7,2%-%date:~4,2%-%date:~10,4%_%time:~,8%

echo %dt%

Then I use the copy command as shown below:

copy result_accnum.txt C:\ramki_windows\batch_practise\Query_stored\result_accnum_%dt%.txt

but nothing useful. I get an error: "The file name, directory name, or volume label syntax is incorrect."

+4
source share
5 answers

A colon ( :) is not allowed in the file name. It is reserved for distinguishing drive letters, etc. In DOS path names. Instead, you can use the underscore ( _) character :

set dt=%date:~7,2%-%date:~4,2%-%date:~10,4%_%time:~0,2%_%time:~3,2%_%time:~6,2%

, 10:00 . , :

set hh=%time:~0,2%
if "%time:~0,1%"==" " set hh=0%hh:~1,1%   

set dt=%date:~7,2%-%date:~4,2%-%date:~10,4%_%hh%_%time:~3,2%_%time:~6,2%
+11
FOR /f "tokens=1-8 delims=:./ " %%G IN ("%date%_%time%") DO (
SET datetime=%%G%%H%%I_%%J_%%K
)

date_hour_min_sec , datetime.

24042015_19_10_12

datetime, , , DOS ( : set filename= sampletextfor_%datetime%.txt sampletextfor_24042015_19_10_12.txt ).


?

for , % date %% time%. % date %% time% cmd ( ). , . , , , . /:. . "" () ( , /)


, !:)

+3

lurker , HH , , 2

set hh=%time:~0,2%
if "%time:~0,1%"==" " set hh=0%hh:~1,1%   

set dt=%date:~7,2%-%date:~4,2%-%date:~10,4%_%hh:~0,2%_%time:~3,2%_%time:~6,2%

for those who like MM-dd-yyyy

set hh=%time:~0,2%
if "%time:~0,1%"==" " set hh=0%hh:~1,1%   

set dt=%date:~4,2%-%date:~7,2%-%date:~10,4%_%hh:~0,2%_%time:~3,2%_%time:~6,2%
+3
source

Here is the complete batch file that worked for me.

@echo off
@SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "tokens=1-8 delims=:./ " %%G IN ("%date%_%time%") DO (
SET datetime=%%G%%H%%I_%%J_%%K
)

copy result_accnum.txt "C:\ramki_windows\batch_practise\Query_stored\result_accnum_!datetime!.txt"

The created file was named as result_accnum_Fri0106_2017_14_54.txt

To create a directory based on a timestamp, the following worked for me.

@echo off
@SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "tokens=1-8 delims=:./ " %%G IN ("%date%_%time%") DO (
SET datetime=%%G%%H%%I_%%J_%%K
)

SET dirname=C:\ramki_windows\batch_practise\Query_stored\result_accnum_!datetime!
if not exist %dirname% mkdir %dirname%

copy result_accnum.txt %dirname%\result_accnum_!datetime!.txt
+1
source

Until 10:00, the file name will have a space, i.e. name_11_11_2014_ 9_45.txt, and the copy will fail. You need to add quotes, i.e.copy name.txt "name%dt%.txt"

0
source

Source: https://habr.com/ru/post/1537548/


All Articles