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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7727114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:48:17  来源:igfitidea点击:

Batch command date and time in file name

windowsbatch-filecommand-linecmd

提问by Raj More

I am compressing files using WinZipon 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.

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

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

Output

输出

Archive_20111011_ 93609.zip

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

但是,我的问题是AMPM。AM 时间戳为我提供了时间9(带有前导空格)与10自然占用两个空格的时间。

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

我想我的问题也会扩展到前 9 天、前 9 个月等。

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

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

回答by Stephan

Another solution:

另一种解决方案:

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>  )

From here, it is easy:

从这里开始,很容易:

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

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

对于 Logan 对文件“修改日期时间”的相同输出格式的请求:

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%

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

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

回答by Alex K.

Extract the hour, look for a leading space, if found replace with a zero;

提取小时,寻找前导空格,如果找到则用零替换;

set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip

回答by WxGuy

You should search; you can simply replace all spaces with zero set hr=%hr: =0%jebOct 11 '11 at 14:16

你应该搜索;您可以简单地用零替换所有空格set hr=%hr: =0%jeb 2011 年10 月 11 日 14:16

So I did:

所以我做了:

set hr=%time:~0,2%
set hr=%hr: =0%

Then use %hr%inside whatever string you are formatting to always get a two-digit hour.

然后%hr%在您要格式化的任何字符串中使用,以始终获得两位数的小时。

(Jeb's comment under the most popular answer worked the best for me and is the simplest. I repost it here to make it more obvious for future users.)

(Jeb 在最受欢迎的答案下的评论对我来说效果最好,也是最简单的。我将其重新发布在此处,以使其对未来的用户更加明显。)

回答by PA.

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.

正如 Vicky 已经指出的那样,%DATE%%TIME%使用完全(无限)可定制的短日期和时间格式返回当前日期和时间。

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

一个用户可以将其系统配置为返回 Fri040811 08.03PM 而另一个用户可以选择 08/04/2011 20:30。

It's a complete nightmare for a BAT programmer.

对于 BAT 程序员来说,这是一场彻头彻尾的噩梦。

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.

将格式更改为固定格式可能会解决问题,前提是您在离开 BAT 文件之前恢复以前的格式。但它可能会受到恶劣的竞争条件的影响,并使取消的 BAT 文件恢复变得复杂。

Fortunately, there is an alternative.

幸运的是,还有另一种选择。

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

您可以改用 WMIC。WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table以不变的方式返回日期和时间。直接用FOR /F命令解析非常方便。

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
 )

回答by Nesar

I found the best solution for me, after reading all your answers:

在阅读了您的所有答案后,我找到了最适合我的解决方案:

set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"

If AM I get 20160915_ 150101(with a leading space and time).

如果是我得到20160915_ 150101(以领先的空间和时间)。

If PM I get 20160915_2150101.

如果 PM 我得到20160915_2150101

回答by Vicky

You can add leading zeroes to a variable (value up to 99) like this in batch: IF 1%Var% LSS 100 SET Var=0%Var%

您可以批量添加前导零到变量(值高达 99),如下所示: IF 1%Var% LSS 100 SET Var=0%Var%

So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.

因此,您需要将日期和时间组件解析为单独的变量,像这样处理它们,然后将它们重新连接在一起以创建文件名。

However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:

但是,解析日期和时间的基础方法取决于系统区域设置。如果您对代码不能移植到其他机器感到高兴,那可能没问题,但是如果您希望它在不同的国际环境中工作,那么您将需要一种不同的方法,例如读取注册表设置:

HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero

(That last one controls whether there is a leading zero on times, but not dates as far as I know).

(最后一个控制时间是否有前导零,但据我所知没有日期)。

回答by user1189773

@For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(

Set DayW=%%A

Set Day=%%B

Set Month=%%C


Set Year=%%D


Set All=%%D%%B%%C
)
"C:\Windows\CWBZIP.EXE" "c:\transfer\ziptest%All%.zip" "C:\transfer\MB5L.txt"

This takes MB5L.txt and compresses it to ziptest20120204.zip if run on 4 Feb 2012

如果在 2012 年 2 月 4 日运行,这需要 MB5L.txt 并将其压缩为 ziptest20120204.zip

回答by user2757848

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

回答by jeb

Your question seems to be solved, but ...

你的问题似乎已经解决了,但是......

I'm not sure if you take the right solution for your problem.
I suppose you try to compress each day the actual project code.

我不确定您是否为您的问题采取了正确的解决方案。
我想你每天都在尝试压缩实际的项目代码。

It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.

使用 ZIP 和 1980 是可能的,这是一个很好的解决方案,但是今天您应该使用存储库系统,例如 subversion 或 git 或 ...,但不能使用 zip 文件。

Ok, perhaps it could be that I'm wrong.

好吧,也许是我错了。

回答by corlettk

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.

我意识到这对 OP 来说是一个没有实际意义的问题,但我刚刚酝酿了这个,我为自己跳出框框思考而感到有点自豪。

Download gawkfor 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)

http://gnuwin32.sourceforge.net/packages/gawk.htm下载适用于 Windows 的gawk.... 然后它是一个单行程序,没有那些笨重的 DOS 批处理语法,它需要六个 FOR 循环来拆分字符串(WTF ?那真的很糟糕,很生气很伤心!......当然恕我直言)

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!!!

如果您已经了解 C、C++、Perl 或 Ruby,那么选择AWK(它继承了前两者,并对后两者做出了重大贡献)是众所周知的蛋糕!

The DOS Batch command:

DOS批处理命令:

echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", , , , , , );}"

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.

现在这还不是完整的故事......我只是懒惰并在 printf 语句中硬编码我的日志文件名的其余部分,因为它很简单......但是如果有人知道如何设置%NOW% 变量到 AWK 的输出(使“通用”现在函数的胆量大吃一惊)然后我全神贯注。



EDIT:

编辑:

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

对 Stack Overflow 的快速搜索填补了最后一块拼图,即 Bash 反引号的 Batch 等效项

So, these three lines of DOS batch:

所以,这三行DOS批处理:

echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", , , , , , );}" >%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:

所以现在我可以在我的 SQL Server 安装(2005+)脚本生成的日志文件的名称中包含一个日期时间:

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).

我再次成为一个快乐的露营者(除了在 Unix 上生活仍然非常轻松)。