How to calculate time duration in Linux?

I want to calculate duration for below file in this format

SID   |   Date     |   Starttime   |Date         |End  time
 1607 |2019-04-05|13:06:42|2019-04-05|13:07:12
 2327 |2019-04-05|13:57:26|2019-04-05|13:57:43

O/p should be like this:

SID   |  Date     |   Starttime   |Date      |Endtime | Duration
 1607 |2019-04-05|13:06:42|2019-04-05|13:07:12  |  ?
 2327 |2019-04-05|13:57:26|2019-04-05|13:57:43  |  ?

Best to convert a formatted time string to a unix timestamp, then do your math, then convert the resulting unix timestamp back to a formatted time string.

With Linux you should have GNU date available. Try

awk -F\|   '
        {printf "%s", "echo \"" $0 " |"
        }
NR == 1 {print " Duration\""
        }
NR > 1  {print  "$(( $(date +%s -d\"" $4 " " $5 "\") - $(date +%s -d\"" $2 " " $3 "\") )) \""
        }
' file | sh

SID   |   Date     |   Starttime   |Date         |End  time | Duration
 1607 |2019-04-05|13:06:42|2019-04-05|13:07:12 |30 
 2327 |2019-04-05|13:57:26|2019-04-05|13:57:43 |17

Two caveats:
1) with your data structure, the system won't know if you're talking 5th April, or 4th May.
2) Above will calculate difference in seconds only. No further formatting like HH:MM:SS will be done; that'll be up to you (search these forums, for example)

1 Like

It is always best to always get in the habit of converting time text string (formatted time) to a unix timestamp (a number).

Then, format the timestamp(s) math results as needed.

It's always best in programming to separate the time functions and processing of time from the formatting of strings, because it is trivial to convert strings to timestamps and timestamps to formatted strings.

FYI, Just about every date stored in our database here at unix.com is a unix timestamp. We generally don't store formatted date strings in DB tables (unless of course the date is part of some text in a post).

Thanks for reply.
i want complete formatting in HH:MM:SS .
1st query

SID   |   Start Date     |   Start time   |End Date         |End  time | Duration
 1607 |2019-04-05|13:06:42|2019-04-05|18:08:12 |?
 2327 |2019-04-05|13:57:26|2019-04-05|19:03:43 |?

2nd query if i am entering in next date then how will calculate duration for example 5th April To 6th April.

SID   |   Start Date     |   Start    time   |End Date         |End  time | Duration
 1607 |2019-04-05|13:06:42|2019-04-06|18:08:12 |?
 2327 |2019-04-05|13:57:26|2019-04-06|19:03:43 |?