Generate unique file name with timestamp in batch script

前端 未结 7 1199
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 13:07

In my .bat file I want to generate a unique name for files/directories based on date-time.

e.g.

Build-2009-10-29-10-59-00

The probl

7条回答
  •  甜味超标
    2020-12-13 13:31

    If you can guarantee that the machine has a specific version of Python installed on it and accessible in the system's PATH, you can use this solution:

    FOR /F "tokens=* USEBACKQ" %%F IN (`python -c "import datetime; print 
    datetime.datetime.now().replace(microsecond=0).isoformat().replace(':', '-')"`) DO (
    SET TIMESTAMP=%%F
    )
    ECHO %TIMESTAMP%
    

    This will put the current local ISO-8601(ish) date representation into a %TIMESTAMP% variable and echo it out, like so:

    2017-05-25T14:54:37
    

    I've put replace(':', '-') after the isoformat() so that the resultant string can be used in a filename or directory, since : is a forbidden character in the Windows filesystem.

提交回复
热议问题