文件名中的批处理命令日期和时间 [英] Batch command date and time in file name
问题描述
我正在命令行上使用 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
然而,我的问题是AM 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.
我想我的问题也会扩展到前 9 天、前 9 个月等.
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>+/-<minutes difference to UTC> )
从这里开始,很容易:
set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023
对于 Logan 对文件的修改日期时间"的相同输出格式的请求:
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
期望反斜杠加倍并且 =
必须被转义(第一个. 第二个由周围的引号保护).
It is 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).
这篇关于文件名中的批处理命令日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!