简体   繁体   中英

Writing Python date to bat file variable

There's tons of half-working examples of how to get the date using batch file syntax, but they are usually overly verbose or difficult to understand. Since I can guarantee that the machine will be running Python, I was hoping to leverage Python to get the date in a nice user-friendly format and write the output to a bat file variable.

This is my attempt:

FOR /F "tokens=* USEBACKQ" %%F IN (`python -c "import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()"`) DO (
SET var=%%F
)
ECHO %var%

Unfortunately this does not work. I get this error:

.replace(microsecond was unexpected at this time.

i'm not sure if I'm missing some kind of formatting, but searches regarding this error yield nothing illuminating. Any help is appreciated.

Try this (though you hadn't specified the python version):

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

echo %var%

you need the print function (otherwise there will be no output to be handled by the batch file)

For more complicated code I would recommend you to use the "chimera" technique by siberia-man which allows you to put both python and batch code in one file with new lines and etc. :

0<0# : ^
''' 
@echo off

for /f "tokens=* delims=" %%a in ('python "%~f0" %*') do (
    set "var=%%a"
)
echo %var%
exit /b 0

:::: PYTHON CODE GOES HERE  :::::
'''

import datetime;

print datetime.datetime.now().replace(microsecond=0).isoformat();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM