Find the answer to your Linux question:
Results 1 to 4 of 4
Hi All, Can some one help. How do I go about writing a script to subtract 1 time value from another? ie: 16:41:39 - 15:23:35 ----------- result =? Thanks Newbie....
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Dec 2003
    Posts
    2

    Help with subtracting time values?


    Hi All,

    Can some one help.
    How do I go about writing a script to subtract 1 time value from another?
    ie:

    16:41:39 -
    15:23:35
    -----------
    result =?


    Thanks

    Newbie.

  2. #2
    Just Joined!
    Join Date
    Dec 2003
    Posts
    14
    I'm not experienced in script programming, but the standard date program may help. Give it the date, like this:
    Code:
    date -d 16:41:39 +%s
    and it will output the date in seconds. In other words, it outputs the current date at that time in seconds.

    Hope this gets you started.

  3. #3
    Just Joined!
    Join Date
    Dec 2003
    Posts
    1

    Help subtracting time

    This is an example, use it however you want. I am not sure how much you know so I will not bore you explaining what I did, unless you ask.

    William

    Code:
    #variables
    #ft% are from the first time
    #st% are from the second time
    #dt% difference time
    
    #cut out the hours minutes seconds
    
    fth=`echo "$ft" | cut -c1-2`
    ftm=`echo "$ft" | cut -c4-5`
    fts=`echo "$ft" | cut -c7-8`
    sth=`echo "$st" | cut -c1-2`
    stm=`echo "$st" | cut -c4-5`
    sts=`echo "$st" | cut -c7-8`
    
    
    
    # do the math for seconds
    
    dts=`expr $sts - $fts`
    if [ $dts -lt 0 ]
    then
    	dts=`expr $dts + 60`
    	ftm=`expr $ftm + 1`
    fi
    for val in $dts
    do
    	if [ $val -lt 10 ]
    	then
    		dts=`echo "0$val"`
    	else
    		dts=`echo $val`
    	fi
    done
    
    
    
    # do the math for minutes
    
    dtm=`expr $stm - $ftm`
    if [ $dtm -lt 0 ]
    then
    	dtm=`expr $dtm + 60`
    	fth=`expr $fth + 1`
    fi
    for val in $dtm
    do
    	if [ $val -lt 10 ]
    	then
    		dtm=`echo "0$val"`
    	else
    		dtm=`echo $val`
    	fi
    done
    
    
    
    # do the math for hours
    
    dth=`expr $sth - $fth`
    
    
    
    # put dtime back together
    
    difftime=`echo $dth:$dtm:$dts`

  4. $spacer_open
    $spacer_close
  5. #4
    Just Joined!
    Join Date
    Dec 2003
    Posts
    2
    @Jman

    Thanks, but I'm using a minimal linux distro & it doesn't have this option.
    Plus converting back, when finished with the calcs is a bit of a worry.

    @zyrotec

    Many thanks,
    This is great saves me a lot of heart-ache & head scratching. It'll get me well on my way.


    CK. :wink:

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •