datetime - 如何在Windows命令行上获取当前的日期时间,以适合的格式在文件名中使用?




command-line batch-file (22)

Given a known locality, for reference in functional form. The ECHOTIMESTAMP call shows how to get the timestamp into a variable ( DTS in this example.)

@ECHO off

CALL :ECHOTIMESTAMP
GOTO END

:TIMESTAMP
SETLOCAL  EnableDelayedExpansion
    SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
    SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
    SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF

:ECHOTIMESTAMP
SETLOCAL
    CALL :TIMESTAMP DTS
    ECHO %DTS%
ENDLOCAL
GOTO :EOF

:END

EXIT /b 0

And saved to file, timestamp.bat, here's the output:

更新:现在是2016年,我会使用PowerShell进行此操作,除非有非常令人信服的向后兼容原因,特别是因为使用date的区域设置问题。 请参阅@npocmaka的https://.com/a/19799236/8479

什么是Windows命令行语句我可以使用什么格式来获取当前日期时间,我可以将它放入文件名?

我想要一个.bat文件,将当前日期和时间作为名称的一部分压缩到一个存档中,例如Code_2008-10-14_2257.zip 。 有没有简单的方法可以做到这一点,独立于机器的区域设置?

我真的不介意日期格式,理想情况下它会是yyyy-mm-dd,但任何简单的事情都可以。

到目前为止,我已经得到了这个,在我的机器上给了我Tue_10_14_2008_230050_91

rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%

rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code

我可以忍受这一点,但似乎有点笨重。 理想情况下,它会更简短,并具有前面提到的格式。

我正在使用Windows Server 2003和Windows XP Professional。 我不想安装额外的实用程序来实现这一点(虽然我意识到有一些会做好日期格式)。


只需使用这一行:

PowerShell -Command "get-date"

这里是时间部分的类似批处理文件。

:: http://.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
      set 'hh'=%%i
      set 'mm'=%%j
      set 'ss'=%%k
      set 'ff'=%%l)
    ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%

    ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
    set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
    echo %timestring%

    :EOF

--jeroen


另一种方式( credit ):

@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @( 
    Set Month=%%A
    Set Day=%%B
    Set Year=%%C
)

@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%

请注意,我的答案仍然依赖区域设置确定的日期和月份的顺序 - 不确定如何解决该问题。


一个基于wmic函数:

:Now  -- Gets the current date and time into separate variables
::    %~1: [out] Year
::    %~2: [out] Month
::    %~3: [out] Day
::    %~4: [out] Hour
::    %~5: [out] Minute
::    %~6: [out] Second
  setlocal
  for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
  endlocal & (
    if "%~1" neq "" set %~1=%T:~0,4%
    if "%~2" neq "" set %~2=%T:~4,2%
    if "%~3" neq "" set %~3=%T:~6,2%
    if "%~4" neq "" set %~4=%T:~8,2%
    if "%~5" neq "" set %~5=%T:~10,2%
    if "%~6" neq "" set %~6=%T:~12,2%
  )
goto:eof

上行:地区独立。 缺点:只有系统管理员才能运行wmic.exe。

用法:

call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%

这回响了一个像这样的字符串:

2014-01-22 12:51:53

请注意,函数参数是out参数 - 也就是说,您必须提供变量名称而不是值。

所有参数都是可选的,所以call:Now YM如果您只想获得年份和月份, call:Now YM是有效的通话。


date.exe

Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).

Put it in your Windows system32 folder.

It has a lot of "date output" options.

For help, use DateFormat.exe --h

I'm not sure how you would put its output into an environment variable... using SET.


马修约翰逊的单线解决方案获得单线日期和时间是雄辩和有用的。

但是,它需要一个简单的修改来从批处理文件中进行工作:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e

Regional independent solution generating the ISO date format:

rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format 
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:

What could still be optimized: Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated


With Windows 7, this code works for me:

SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%

SET DATE_FRM=%YEAR%-%MONTH%-%DAY% 
ECHO %DATE_FRM%

区域独立的日期时间解析

%DATE%dir命令的输出格式是区域相关的,因此既不健壮也不智能。 date.exeUnxUtils一部分)以任何可想象的格式提供任何日期和时间信息。 您也可以使用date.exe从任何文件中提取日期/时间信息。

示例:(在cmd脚本中使用%%而不是%)

date.exe +"%Y-%m-%d"
2009-12-22

date.exe +"%T"
18时55分03秒

date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503:任何文字

date.exe +"Text: %y/%m/%d-any text-%H.%M"
文本:09/12 / 22-任何文本-18.55

Command: date.exe +"%m-%d """%H %M %S """"
07-22“18:55:03”`

来自参考文件的日期/时间信息:
date.exe -rc:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

在CMD脚本中使用它获取年,月,日,时间信息:

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

在CMD脚本中使用它获取任何所需格式的时间戳:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i

从任何参考文件中提取日期/时间信息。

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

向文件添加日期/时间信息:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt

date.exe是不需要安装date.exe

注意:将date.exe复制到搜索路径中的任何目录可能会导致其他脚本失败,并使用Windows内置date命令。


:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 [email protected]
:: - http://.com/questions/203090
@echo off

set _isotime=
set _now=

:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_

if not (%1)==() goto _help
SetLocal EnableDelayedExpansion

:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF "%%~L"=="" goto  _WMIC_done_
        set _yyyy=%%L
        set _mm=00%%J
        set _dd=00%%G
        set _hour=00%%H
        set _minute=00%%I
        set _second=00%%K
)
:_WMIC_done_

::   1    2     3       4      5      6
:: %%G  %%H    %%I     %%J    %%K    %%L
:: Day  Hour  Minute  Month  Second  Year
:: 27   9     35      4      38      2017

:: Remove excess leading zeroes
        set _mm=%_mm:~-2%
        set _dd=%_dd:~-2%
        set _hour=%_hour:~-2%
        set _minute=%_minute:~-2%
        set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%

:: Set date/time in ISO 8601 format:
        Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format

if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
    set /a _hour=1%_hour%-12
    set _hour=%_hour:~-2%
    set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
    :: -> https://ss64.com/nt/if.html
    :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
    :: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_

EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out

:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"

:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo    %%_now%%     environment variable set to current date and time
echo    %%_isotime%% environment variable to current time in ISO format
echo    set _today=%%_isotime:~0,10%%
echo.

:_out
:: EOF: GetDate.cmd

这是我用过的:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

如果您想要自动备份到7-Zip存档的更多想法,我有一个您可以使用或查看想法的免费/开放项目: http://wittman.org/ziparcy/ : http://wittman.org/ziparcy/


"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip

请参阅Windows批处理文件(.bat)以MMDDYYYY格式获取当前日期

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%

如果你更喜欢24小时/军用格式的时间,你可以用这个替换第二个FOR行:

For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:>。\ date.bat
2008-10-14_0642

如果您想要独立于区域日/月订单的日期,则可以使用“WMIC os GET LocalDateTime”作为源,因为它的格式为ISO顺序:

@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]

C:> TEST.CMD
当地日期为[2012-06-19 10:23:47.048]


我使用的批处理文件更改了答案 ,因此它也适用于荷兰语。
荷兰人 - 像我们一样持久 - 在%date%date/t和打破原始批处理文件的date中有一些变化。

如果有些人可以对其他Windows语言环境进行检查,并返回结果,那将会很不错。
如果批处理文件在您的位置失败,请在命令提示符处包含这两条语句的输出:
echo:^|date
date/t

这是您应该从批处理文件获得的输出示例:

C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103

以下是修改后的代码,并对原因进行了评论:

:: https://.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by [email protected] for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
::            set '%%c'=%%k
::            set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
::        if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
    set v_day=
    set v_month=
    set v_year=

    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
      for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
        if "%%a" GEQ "A" (
          for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
            set '%%a'=%%i
            set '%%b'=%%j
            set 'yy'=%%k
          )
        )
      )
      if %'yy'% LSS 100 set 'yy'=20%'yy'%
      set Today=%'yy'%-%'mm'%-%'dd'%

    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
    set datestring=%V_Year%%V_Month%%V_Day%
    echo %datestring%

    :EOF

--jeroen


不幸的是,这对区域设置不是免疫的,但它可以做到你想要的。

set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%

惊人的东西,你可以找到Wikipedia


此代码的前四行将为您提供Windows XP Professional及更高版本中可靠的YY DD MM YYYY HH Min Sec变量。

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

我有类似的问题。 我有一个自动每日从FTP服务器上下载一个加密文件。 我想使用gpg解密文件,将文件重命名为当前日期(YYYYMMDD格式),并将解密后的文件放入正确部门的文件夹中。

我经历了几次根据日期对文件进行重命名的建议,直到我偶然发现这个简单的解决方案之前,我一直没有运气。

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt

它工作完美(即,文件名为“2011-06-14.txt”)。

(Source)


以下是来自alt.msdos.batch.nt的一个独立于本地的变体。

把它放在一个文本文件中,例如getDate.cmd

-----------8<------8<------------ snip -- snip ----------8<-------------
    :: Works on any NT/2k machine independent of regional date settings
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
    for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
      for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
        set '%%a'=%%i
        set '%%b'=%%j
        set '%%c'=%%k))
    if %'yy'% LSS 100 set 'yy'=20%'yy'%
    set Today=%'yy'%-%'mm'%-%'dd'% 
    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]

    :EOF
-----------8<------8<------------ snip -- snip ----------8<-------------

为了让代码能够正常工作,无需将错误消息添加到stderr中,我必须为%% a,%% b和%% c添加变量赋值的单引号。 我的语言环境(PT)在循环/解析中的某个阶段导致错误,例如“set = 20”的内容正在执行。 引号会为赋值语句的左侧生成一个令牌(虽然为空)。

缺点是混乱的区域设置变量名称:'yy','mm'和'dd'。 但是,嘿,谁在乎!


我用这个(不是区域独立的(英国))

set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%

I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.

:: Check your local date format
echo %date%

    :: Output is Mon 08/15/2016

:: get day (start index, number of characters)
::         (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
    :: output is Mon 

:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
    :: output is 08

:: get date 
set mydate=%DATE:~7,2% 
echo %mydate%
    :: output is 15

:: get year
set myyear=%DATE:~10,4%
echo %myyear%
    :: output is 2016

尝试:

mysql -u username -p database_name < file.sql

检查MySQL选项

注意1:最好使用SQL文件file.sql的完整路径。

注2:使用-R--triggers来保留原始数据库的例程和触发器。 它们不会被默认复制。





windows datetime command-line batch-file