Batch command date and time in file name

前端 未结 14 2043
闹比i
闹比i 2020-11-22 01:25

I am compressing files using WinZip on the command line. Since we archive on a daily basis, I am trying to add date and time to these files so that a new one is auto generat

相关标签:
14条回答
  • 2020-11-22 01:56

    A space is legal in file names. If you put your path and file name in quotes, it may just fly. Here's what I'm using in a batch file:

    svnadmin hotcopy "C:\SourcePath\Folder" "f:\DestPath\Folder%filename%"
    

    It doesn't matter if there are spaces in %filename%.

    0 讨论(0)
  • 2020-11-22 01:57

    As others have already pointed out, the date and time formats of %DATE% and %TIME% (as well as date /T and time /T) are locale-dependent, so extracting the current date and time is always a nightmare, and it is impossible to get a solution that works with all possible formats since there are hardly any format limitations.


    But there is another problem with a code like the following one (let us assume a date format like MM/DD/YYYY and a 12 h time format like h:mm:ss.ff ap where ap is either AM or PM and ff are fractional seconds):

    rem // Resolve AM/PM time:
    set "HOUR=%TIME:~,2%"
    if "%TIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
    if "%TIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
    rem // Left-zero-pad hour:
    set "HOUR=0%HOUR%"
    rem // Build and display date/time string:
    echo %DATE:~-4,4%%DATE:~0,2%%DATE:~3,2%_%HOUR:~-2%%TIME:~3,2%%TIME:~6,2%
    

    Each instance of %DATE% and %TIME% returns the date or time value present at the time of its expansion, therefore the first %DATE% or %TIME% expression might return a different value than the following ones (you can prove that when echoing a long string containing a huge amount of such, preferrably %TIME%, expressions).

    You could improve the aforementioned code to hold a single instance of %DATE% and %TIME% like this:

    rem // Store current date and time once in the same line:
    set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
    rem // Resolve AM/PM time:
    set "HOUR=%CURRTIME:~,2%"
    if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
    if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
    rem // Left-zero-pad hour:
    set "HOUR=0%HOUR%"
    rem // Build and display date/time string:
    echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%
    

    But still, the returned values in %DATE% and %TIME% could reflect different days when executed at midnight.

    The only way to have the same day in %CURRDATE% and %CURRTIME% is this:

    rem // Store current date and time once in the same line:
    set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
    rem // Resolve AM/PM time:
    set "HOUR=%CURRTIME:~,2%"
    if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
    if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
    rem // Fix date/time midnight discrepancy:
    if not "%CURRDATE%" == "%DATE%" if %CURRTIME:~0,2% equ 0 set "CURRDATE=%DATE%"
    rem // Left-zero-pad hour:
    set "HOUR=0%HOUR%"
    rem // Build and display date/time string:
    echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%
    

    Of course the occurrence of the described problem is quite improbable, but at one point it will happen and cause strange unexplainable failures.


    The described problem cannot occur with the approaches based on the wmic command as described in the answer by user Stephan and in the answer by user PA., so I strongly recommend to go for one of them. The only disadvantage of wmic is that it is way slower.

    0 讨论(0)
  • 2020-11-22 01:59

    From the answer above, I have made a ready-to-use function.

    Validated with french local settings.

    :::::::: PROGRAM ::::::::::
    
    call:genname "my file 1.txt"
    echo "%newname%"
    call:genname "my file 2.doc"
    echo "%newname%"
    
    echo.&pause&goto:eof
    :::::::: FUNCTIONS :::::::::
    
    :genname
        set d1=%date:~-4,4%
        set d2=%date:~-10,2%
        set d3=%date:~-7,2%
        set t1=%time:~0,2%
        ::if "%t1:~0,1%" equ " " set t1=0%t1:~1,1%
        set t1=%t1: =0%
        set t2=%time:~3,2%
        set t3=%time:~6,2%
        set filename=%~1
        set newname=%d1%%d2%%d3%_%t1%%t2%%t3%-%filename%
    goto:eof
    
    0 讨论(0)
  • 2020-11-22 02:01

    As Vicky already pointed out, %DATE% and %TIME% return the current date and time using the short date and time formats that are fully (endlessly) customizable.

    One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.

    It's a complete nightmare for a BAT programmer.

    Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.

    Fortunately, there is an alternative.

    You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F command.

    So, putting the pieces together, try this as a starting point...

    SETLOCAL enabledelayedexpansion
    FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
      SET /A FD=%%F*1000000+%%D*100+%%A
      SET /A FT=10000+%%B*100+%%C
      SET FT=!FT:~-4!
      ECHO Archive_!FD!_!FT!.zip
     )
    
    0 讨论(0)
  • 2020-11-22 02:01

    I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.

    Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)

    If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!

    The DOS Batch command:

    echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"
    

    Prints:

    Tue 04/09/2012 10:40:38.25
    20120904-104038
    

    Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.


    EDIT:

    A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.

    So, these three lines of DOS batch:

    echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
    set /p now=<%temp%\now.txt
    echo %now%
    

    Produce:

    20120904-114434
    

    So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:

    sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log
    

    And I'm a happy camper again (except life was still SOOOOO much easier on Unix).

    0 讨论(0)
  • 2020-11-22 02:01

    I prever to use this over the current accepted answer from Stephan as it makes it possible to configure the timestamp using named parameters after that:

    for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x

    It will provide the following parameters:

    • Day
    • DayOfWeek
    • Hour
    • Milliseconds
    • Minute
    • Month
    • Quarter
    • Second
    • WeekInMonth
    • Year

    You can then configure your format like so:

    SET DATE=%Year%%Month%%Day%

    0 讨论(0)
提交回复
热议问题