Convert Date from File and Calculate Duration

Hi - I am looking for a little help to read in 2 date fields from a file in format:

20120508134012.3
yyyymmddhhmmss.tenths of a second

So i want to:

  1. Read in the 1st date from the file
  2. Read in the second date from the file
  3. Calculate the difference in minutes (or seconds)
  4. Append the line of the original file with the "duration".

I am guessing the best approach would be to convert the date/times to epoch time, and subract. I have been searching the threads, but have not come up with anything. Any thoughts?

Thanks!

You've got the right idea, but converting that to epoch time can either be easy or painful depending on what your system is. What is it?

Thanks - Here is output from uname -a

Linux as1 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux

date -d saves you a lot of pain when you have it, but is Linux-only.

I have in filename:

2010100912000145
2010100912000955

And the script:

#!/bin/bash

exec 5<filename    # Open file into FD 5
read T1 <&5
read T2 <&5

# Arrange them how GNU date wants it YYYYMMDD HH:MM:SS.SS
T1="${T1:0:8} ${T1:8:2}:${T1:10:2}:${T1:12:2}.${T1:14}"
T2="${T2:0:8} ${T2:8:2}:${T2:10:2}:${T2:12:2}.${T2:14}"

# Convert into epoch seconds
E1=$(date -d "$T1" +%s)
E2=$(date -d "$T2" +%s)

echo "E2-E1 = $((E2-E1))"

exec 5<&-       # Close FD 5

does this:

E2-E1 = 8
2 Likes

Sweet! This is perfect!

If you are using the ksh93 shell:

exec 5<filename
read T1 <&5
read T2 <&5
exec 5<&-

E1=$( printf "%(%s)T" "${T1:0:8} ${T1:8:2}:${T1:10:2}:${T1:12:2}.${T1:14}" )
E2=$( printf "%(%s)T" "${T2:0:8} ${T2:8:2}:${T2:10:2}:${T2:12:2}.${T2:14}" )

echo "E2-E1 = $((E2-E1))"
2 Likes