LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how to get difference between two times (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-get-difference-between-two-times-693834/)

prasanta_das 12-30-2008 05:56 AM

how to get difference between two times
 
STARTING 06:12:23

SUCCESS 06:19:41


how to get diff of two times

prasanta_das 12-30-2008 06:05 AM

start
5:34:06 5:34:14 0:00:08

prasanta_das 12-30-2008 06:05 AM

can someone do me a favor for the above

Telemachos 12-30-2008 06:32 AM

My advice would be to (1) convert your times (as you get them) to epoch time and (2) then take the difference of those two. You can then (3) convert the difference into a more human-friendly time format whenever you need.

Example (using your first request):
Code:

06:12:23 or epoch time: 1230617543

06:19:41 or epoch time: 1230617981

438 seconds difference or 7 minutes and 18 seconds

You will need to write a program to take in the two timestamps and do the computations, if you plan to do this regularly. Here are a few links to sites that can show you what's involved.

http://www.epochconverter.com/
http://www.csgnetwork.com/epochtime.html

The first website has short, but helpful discussions about how to compute epoch time from "human" formats and vice versa in various languages.

Edit: I'm assuming that you want help doing this with a program and not that you just want us to do the math for you.

arckane 12-30-2008 06:41 AM

Or use nano seconds -
Code:

date +%N

colucix 12-30-2008 07:01 AM

You have also to check if the END time is smaller or greater than the START time. For example if a job starts at 23:45:09 and terminates at 00:23:18 you have to take in account the change of day in your calculations (to not mention the troubles introduced by the passage from/to the Daylight Saving Time).

Anyway, here is an example of what you can do:
Code:

#!/bin/bash
START=23:58:56
END=00:45:00

if [[ $END < $START ]]
then
  elapsed=$(date -d "00:00:00 $(($(date -d "19700102 $END" +%s) - \
          $(date -d "19700101 $START" +%s))) seconds" +%H:%M:%S)
else
  elapsed=$(date -d "00:00:00 $(($(date -d "19700101 $END" +%s) - \
          $(date -d "19700101 $START" +%s))) seconds" +%H:%M:%S)
fi

echo $elapsed

END and START must be in HH:MM:SS format to let the above code work, since the comparison is done by ASCII order (string comparison).

David1357 12-30-2008 09:21 AM

Quote:

Originally Posted by prasanta_das (Post 3391405)
how to get diff of two times

Here's a script that I posted as an answer to a similar question in another thread.

This script will show you how to convert a time to seconds since the epoch. You can then compare the seconds.


All times are GMT -5. The time now is 01:51 AM.