14

I'd like to have a time, say 6:45am, and add an amount of hours, say 1.45 hours, to result in another time. So I'd like to add 1.45 hours to 6:45am to get another time.

Is there a command line utile for that? I've done some Googling, and read the man page for date and haven't found anything like that. wcalc doesn't seem to handle time calculations.

EDIT: Mar 6, 2015. This is the script I ended up with to use decimal hours. It could use some error checking to make sure HH:MM uses 2 digits for the hours.

#!/bin/bash
# Mar 6, 2015
# Add decimal hours to given time. 
# Syntax: timeadd HH:MM HOURS
# There MUST be 2 digits for the hours in HH:MM.
# Times must be in military time. 
# Ex: timeadd 05:51 4.51
# Ex: timeadd 14:12 2.05
echo " "
# If we have less than 2 parameters, show instructions and exit.
if [ $# -lt 2 ]
then
    echo "Usage: timeadd HH:MM DECHOURS"
    exit 1
fi
intime=$1
inhours=$2
# Below is arithmetic expansion $(())
# The bc calculator is standard on Ubuntu. 
# Below rounds to the minute. 
inminutes=$(echo "scale=0; ((($inhours * 60)*10)+5)/10" | bc)
echo "inminutes=$inminutes"
now=$(date -d "$intime today + $inminutes minutes" +'%H:%M')
echo "New time is $now"
23

Command line:

$ now=$(date -d "06:45 today + 105 minutes" +'%H:%M')
$ echo "$now"
08:30

$now will hold the time you specified.

You can put a lot of things in between the " and "; like the current time and add 105 to it.


$now=$(date -d "06:45 today + 2.5 hour" +'%H:%M')
date: invalid date `06:45 today + 2.5 hour'
$now=$(date -d "06:45 today + 2:30 hour" +'%H:%M')
date: invalid date `06:45 today + 2:30 hour'
$ now=$(date -d "06:45 today + 2 hour" +'%H:%M')
$ echo "$now"
08:45

No decimals allowed...


From comments: To get the answer for 1.45 decimal hours:

$ now=$(date -d "06:45 today + $((145 * 60 / 100)) minutes" +'%H:%M')
$ echo "$now:
8:12
  • Squeee! Thank you! I had trouble reading the last part, but the part around the %H:%M are two single quotes. Is there any way to do this in decimal hours instead of converting it to minutes? That would eliminate a step. I'd even be open to installing a special calculator. I do appreciate your work though, please don't misunderstand. – Bulrush Dec 24 '14 at 13:36
  • "+10 days" works too. So does "+2 hour". Of course you could also add a method here to make minutes from 2.5 hours ;) I never found a full list of words you can use... – Rinzwind Dec 24 '14 at 14:38
  • @Bulrush hmm no decimals allowed with hour :D – Rinzwind Dec 24 '14 at 14:50
  • @Rinzwind I'm not sure but did you try 2:30 hour instead of 2.5 hour? – αғsнιη Dec 24 '14 at 15:02
  • 1
    @Rinzwind So one possible is using 2 hour + 30 minutes ;) – αғsнιη Dec 24 '14 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.