Bash: calculate the time elapsed between two timestamps

This will give you the date in seconds (since the UNIX epoch)

date --date '2017-08-17 04:00:01' +%s    # "1502938801"

And this will give you the date as a readable string from a number of seconds

date --date '@1502938801'    # "17 Aug 2017 04:00:01"

So all that's needed is to convert your date/timestamp into a format that GNU date can understand, use maths to determine the difference, and output the result

datetime1=20170817040001
datetime2=20160312000101

seconds1=$(date --date "$(echo "$datetime1" | sed -nr 's/(....)(..)(..)(..)(..)(..)/\1-\2-\3 \4:\5:\6/p')" +%s)
seconds2=$(date --date "$(echo "$datetime2" | sed -nr 's/(....)(..)(..)(..)(..)(..)/\1-\2-\3 \4:\5:\6/p')" +%s)

delta=$((seconds1 - seconds2))
echo "$delta seconds"    # "45197940 seconds"

We've not provided timezone information here so it assumes local timezone. Your values for the seconds from the datetime will probably be different to mine. (If your values are UTC then you can use date --utc.)


This is easy with datediff command provided in dateutils package.

ddiff -i '%Y%m%d%H%M%S' 20170817040001 20160312000101