3

I am looking to write a shell script that will compare the time between two date-time stamps in the format:

2013-12-10 13:25:30.123
2013-12-10 13:25:31.123

I can split the date and time if required (as the comparison should never be more than one second - I am looking at a reporting rate), so I can format the time as 13:25:30.123 / 13:25:31.123.

Dustin Cook
  • 1,215
  • 5
  • 26
  • 44
  • What do you mean by compare?? giving the greatest or least or difference??? – Srini V Dec 10 '13 at 14:31
  • What do you mean by "compare"? Do you just need to select the newest / oldest one? Do you need the time difference? ... – MarcoS Dec 10 '13 at 14:32
  • I am looking to find the time difference between the two stamps. Sorry I appreciate that I wasn't clear on that. – Dustin Cook Dec 10 '13 at 14:42
  • Not a duplicate question - I am looking for the time accuracy down to milliseconds. – Dustin Cook Dec 10 '13 at 15:13
  • Still looks like a duplicate, just not an exact one. Solving for millisecond instead of hour, the method to solution is the same. – Greg Mar 01 '14 at 02:02

3 Answers3

4

To just find the newer (or older) of the two timestamps, you could just use a string comparison operator:

time1="2013-12-10 13:25:30.123"
time2="2013-12-10 13:25:31.123"

if [ "$time1" > "$time2" ]; then
    echo "the 2nd timestamp is newer"
else
    echo "the 1st timestamp is newer"
fi

And, to find the time difference (tested):

ns1=$(date --date "$time1" +%s%N)
ns2=$(date --date "$time2" +%s%N)
echo "the difference in seconds is:" `bc <<< "scale=3; ($ns2 - $ns1) / 1000000000"` "seconds"

Which, in your case prints

the difference in seconds is: 1.000 seconds
MarcoS
  • 17,323
  • 24
  • 96
  • 174
3

Convert them into timestamps before comparing:

if [ $(date -d "2013-12-10 13:25:31.123" +%s) -gt $(date -d "2013-12-10 13:25:30.123" +%s) ]; then
  echo "blub";
fi
chaos
  • 8,162
  • 3
  • 33
  • 40
0

With Perl using the included Time::Piece library:

perl -MTime::Piece -nE '
    BEGIN {
        $, = "\t";
        sub to_seconds {
            my ($dt, $frac) = (shift =~ /(.*)(\.\d*)$/);
            return(Time::Piece->strptime($dt, "%Y-%m-%d %T")->epoch + $frac);
        }
    }
    if ($. > 1) {
        $a = to_seconds($_); 
        $b = to_seconds($prev); 
        say $a, $b, $a-$b
    } 
    $prev = $_
'<<END
2013-12-10 13:25:30.123
2013-12-10 13:25:31.123
2013-12-10 13:25:42.042
END
1386681931.123  1386681930.123  1
1386681942.042  1386681931.123  10.9190001487732
glenn jackman
  • 238,783
  • 38
  • 220
  • 352