Compare two timestamps and print elapsed time

Hi,
I am unable to Difference between two time stamps in Linux and display the total elapsed time .

Source date: Aug 15, 2012 02:00:03
Target date: Aug 14, 2012 18:00:03

# based on the forums I am using the below function. Converted dates into this format

Src_dt=20120814180003
Tgt_dt=20120815020003
Total=`expr $Tgt_dt - $Src_dt`
Echo $Total

I am unable to get the proper output. I should get like this (total elapsed time: 08:00:00).

Does Linux having any direct command to difference between two timestamps and giving the total elapsed time,

Any suggestions, greatly appreciated.

Thanks
onesuri

One way would be to use the special date formatting capabilities of the printf builtin of the kornshell 93:

#!/bin/ksh93

src=$( printf "%(%s)T\n" 201208141800.03 )
tgt=$( printf "%(%s)T\n" 201208150200.03 )

TZ= printf "%(%T)T\n" '#'$(( tgt - src ))

Output:

08:00:00

Assumed you are talking of file time stamps, the stat --printf "%X" filename will output seconds since epoch, which can easily subtracted/converted. Use %Y or %Z for file's other timestamps.

Hi,

Thanks for the suggestion,
I have tried the same way but I am getting the below error. I am using the LINUX environment. Do i need to use different format for the below commands.

Sample.sh: line 5: printf: `(�: invalid format character
Sample.sh: line 6: printf: `(�: invalid format character
Sample.sh: line 7: printf: `(�: invalid format character

Thanks -onesuri

You seem to use the standard printf command. My solution only works with the kornshell 93 and it's builtin printf command.

Please provide the output for the src,tgt and TZ. it will easy to find the relevent command

src=$( printf "%(%s)T\n" 201208141800.03 )
tgt=$( printf "%(%s)T\n" 201208150200.03 )

TZ= printf "%(%T)T\n" '#'$(( tgt - src ))

src, tgt and TZ are shell variables, not commands. Look for a command "ksh93" on your system (usually /bin/ksh93). If this command is not present, you have to install the kornshell 93 or find a different approach.

---------- Post updated at 11:04 ---------- Previous update was at 11:00 ----------

Ahh, I think I misunderstood you.

src and tgt will hold the timestamps converted to the internal unix time representation

src = 1344960003
tgt = 1344988803

TZ is the timezone variable and has to be cleared, so that the correct time difference is printed, because it is actually not a time difference, but a timestamp relative to the first of january, 1970.

Hi,

Try this

Src_dt="Aug 15, 2012 02:00:03"
Tgt_dt="Aug 14, 2012 18:00:03"
Total=$(expr $(date -d "$Src_dt"  +%s) - $(date -d "$Tgt_dt" +%s))
echo $Total | awk '{printf "Elapsed time: %02d:%02d:%02d\n",$1/(60*60),$1%(60*60)/60,$1%60}'

Output will be.

Elapsed time: 08:00:00