Figuring Out Date and Time Arithmetic

Problem

You need to do some kind of arithmetic with dates and times.

Solution

If you can’t get the answer you need using the date command (see Automating Date Ranges), convert your existing dates and times to Epoch seconds using Converting Dates and Times to Epoch Seconds, perform your calculations, then convert the resulting Epoch seconds back to your desired format using Converting Epoch Seconds to Dates and Times.

Tip

If you don’t have GNU date, you may find the shell functions presented in “Shell Corner: Date-Related Shell Functions” in the September 2005 issue of Unix Review to be very useful. See Automating Date Ranges.

For example, suppose you have log data from a machine where the time was badly off. Everyone should already be using the Network Time Protocol (NTP) so this doesn’t happen, but just suppose:

CORRECTION='172800' # 2 days worth of seconds # Code to extract the date portion from the data # into $bad_date go here # Suppose it's this: bad_date='Jan 2 05:13:05' # syslog formated date # Convert to Epoch using GNU date bad_epoch=$(date -d "$bad_date" '+%s') # Apply correction good_epoch=$(( bad_epoch + $CORRECTION )) # Make corrected date human-readable good_date=$(date -d "1970-01-01 UTC $good_epoch seconds") # GNU Date good_date_iso=$(date -d "1970-01-01 UTC $good_epoch seconds" +'%Y-%m-%d %T') # GNU Date echo "bad_date: $bad_date" echo "bad_epoch: $bad_epoch" echo "Correction: +$CORRECTION" echo "good_epoch: $good_epoch" echo "good_date: ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.