批处理命令日期和时间在文件名中

问题描述:

我在命令行上使用 WinZip 压缩文件。由于我们每天存档,我试图添加日期和时间这些文件,以便每次都自动生成一个新的。

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 generated every time.

我使用下面的生成文件名。复制粘贴到您的命令行,您应该看到一个文件名有一个日期和时间组件。

I use the following to generate a file name. Copy paste it to your command line and you should see a filename with a Date and Time component.

echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.zip

输出

Archive_20111011_ 93609.zip

但我的问题是 vs PM 。 AM时间戳给我时间 9 (具有前导空格)与 10 自然占用两个空格。

However, my issue is AM vs PM. The AM time stamp gives me time 9 (with a leading blank space) vs. 10 naturally taking up the two spaces.

我想我的问题将延伸到前九天,前九个月等。

I guess my issue will extend to the first nine days, first 9 months, etc. as well.

我如何解决这个问题,以便包括前导零,而不是前导空白,所以我得到 Archive_20111011_093609.zip

How do I fix this so that leading zeroes are included instead of leading blank spaces so I get Archive_20111011_093609.zip?

另一个解决方案:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

它会给你(独立于区域设置!):

It will give you (independent of locale settings!):

  20130802203023.304000+120 
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<timedifference to UTC>  )

很容易:

set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023

编辑 29Dec15用于Logan请求相同的outputformat文件的日期时间修改:

Edit 29Dec15 for Logan's request for the same outputformat for the "date-time modified" of a file:

for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%

因为它只适用于完整路径, wmic 期望反斜杠加倍,并且必须转义 = 第一。第二个由周围的报价保护)

A bit more complicated, because it works only with full paths, wmic expects the backslashes to be doubled and the = has to be escaped (the first one. The second one is protected by surrounding quotes)