Search code examples
datetimeunixautosys

How to subtract two times in Unix to get the completion time for autosys job


I want to calculate completion time for an autosys job:

I have below job status in file:

$cat rough
abc_why_the_infra_dnjob               10/05/2017 10:41:36  10/05/2017 12:52:02  SU
abc_why_the_avloqhk_dnjob             10/05/2017 09:53:36  10/05/2017 10:33:03  SU
abc_why_the_avlogsg_dnjob             10/05/2017 10:33:14  10/05/2017 10:41:01  SU
abc_why_the_avalokin_dnjob            10/05/2017 09:37:36  10/05/2017 09:53:06  SU
abc_why_the_mastercard_dnjob          10/05/2017 13:29:36  10/05/2017 14:21:02  SU
abc_why_the_tcs_dnjob                 10/05/2017 03:13:36  10/05/2017 03:22:02  SU
abc_why_the_cogni_dnjob               10/05/2017 09:20:36  10/05/2017 09:37:02  SU
abc_why_the_dnjob                  10/05/2017 03:41:36  10/05/2017 04:08:02  SU

And I wrote the below script to calculate it:


$ cat sod.sh

#!/bin/bash

number=`cat rough| wc -l`

for i in `seq 1 $number`
do

        job_name=`awk -F' ' '{print $1}' rough | sed -n "$i p"`

        START_DATE=`awk -F' ' '{print $2}' rough | sed -n "$i p"`
        END_DATE=`awk -F' ' '{print $4}' rough | sed -n "$i p"`

        START_TIME=`awk -F' ' '{print $3}' rough | sed -n "$i p"`
        END_TIME=`awk -F' ' '{print $5}' rough | sed -n "$i p"`

        if [[ $START_DATE == $END_DATE ]]
        then
                T1=`date --date="${END_DATE} ${END_TIME}" "+%s"`
                T2=`date --date="${START_DATE} ${START_TIME}" "+%s"`

                TIME_DIFFERENCE=`expr $T2 - $T1`
                COMPLITION_TIME=`date -d "@${TIME_DIFFERENCE}" "+%H:%M:%S"`

                echo $COMPLITION_TIME
        fi
done

Output:

$./sod.sh
03:19:34
04:50:33
05:22:13
05:14:30
04:38:34
05:21:34
05:13:34
05:03:34

My Query now: The output is incorrect can you suggest me. I am expecting correct answers like: 02:11 >> for first job


Solution

  • I got an answer using a Python script:

    >>> s1='10:41:36'
    >>> s2='12:52:02'
    >>> import datetime
    >>> import time
    >>> total_time=(datetime.datetime.strptime(s2,'%H:%M:%S') - datetime.datetime.strptime(s1,'%H:%M:%S'))
    >>> print total_time
    2:10:26