Search code examples
batch-filecmdarithmetic-expressions

Converting time to seconds using arithmetic operators


I'm trying to convert a time value from a text file from hr:min:sec.sec to just seconds. I have a file with event numbers (consecutive order, 1,2,3 etc.) in column 1 of each row and the rest of the row is event data as in my example below. I want to have the user enter two numbers, with which my script grabs the corresponding hr:min:sec of each event and converts into only seconds.

The file format is 4 000-01:04:10.983745 34.56 string1 string_2 (this would be the 4th line, its date/time, a duration in seconds, and two static strings in the next two columns.

I am using a for loop to grab tokens 1, 2, and 3 using : as the delims and then just trimming the strings for the purpose of performing arithmetic.

So %%A should be 4 000-01, %%B should be 04, and %%C should be everything else on the line. Now I just read batch doesn't support decmials, so I can do without them if needed. But this isn't returning anything:

setlocal enabledelayedexpansion enableextension

REM auto-setting event values for testing 
set begin=3 
set end=4

for /f "tokens=1,2,3 delims=:" %%A in ('findstr /b /c:"!begin![^0-9]" event.txt') do ( 
    set "hr=%%A" 
    set /A "min=%%B" 
    set "sec=%%C" 
    set /A "hr=!hr:~-2!" 
    set /A "sec=!sec:~0,2!" 
    set /A "total=(hr*3600)+(min*60)+sec" 
    echo !total!>>time.txt
)
exit /B

Solution

  • If your file format is:

    line   4 000-01:04:10.983745 34.56 string1 string_2
    delim       -  :  :  . 
    token    1   2  3  4
    var      -   A  B  C
    

    A common technic to avoid the leading zero/octal problem is to prefix a two place decimal with a literal 1 and subtract 100. Set /A allows multiple calculations on a line seperated by a comma, the vars don't need to be enclosed in percent signs (doesn't apply to for/arg vars).

    @Echo off
    setlocal enabledelayedexpansion enableextensions
    for /f "tokens=2-4 delims=-:." %%A in (
      'findstr /b /C:"4 " event.txt'
    ) do Set /A "hr=1%%A-100,min=1%%B-100,sec=1%%C-100,total=hr*3600+min*60+sec"
    echo Total is %total% (hr=%hr%, min=%min%, sec=%sec%)
    echo %total% >>time.txt
    exit /B
    

    Sample output:

    Total is 3850 (hr=1, min=4,sec=10)