Calculate time difference in hours between two dates and times
To get the total hours between two dates, just subtract and apply the proper format:
Sub INeedADate()
[c1] = [b1] - [a1]
Range("C1").NumberFormat = "[hh]:mm"
End Sub
Difference between two time.Time objects
You may use Time.Sub()
to get the difference between the 2 time.Time
values, result will be a value of time.Duration
.
When printed, a time.Duration
formats itself "intelligently":
t1 := time.Now()
t2 := t1.Add(time.Second * 341)
fmt.Println(t1)
fmt.Println(t2)
diff := t2.Sub(t1)
fmt.Println(diff)
Output:
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:05:41 +0000 UTC
5m41s
If you want the time format HH:mm:ss
, you may constuct a time.Time
value and use its Time.Format()
method like this:
out := time.Time{}.Add(diff)
fmt.Println(out.Format("15:04:05"))
Output:
00:05:41
Try the examples on the Go Playground.
Of course this will only work if the time difference is less than a day. If the difference may be bigger, then it's another story. The result must include days, months and years. Complexity increases significnatly. See this question for details:
golang time.Since() with months and years
The solution presented there solves this issue by showing a function with signature:
func diff(a, b time.Time) (year, month, day, hour, min, sec int)
You may use that even if your times are within 24 hours (in which case year
, month
and day
will be 0
).
Calculating time difference in hours
If you use the Java Date and Time API available in the java.time
package, then it'll becomes much simpler.
static long getDifferenceInHours(ZonedDateTime dateTime) {
ZonedDateTime now = ZonedDateTime.now();
return Duration
.between(dateTime, now)
.toHours();
}
You can then call it like this:
ZonedDateTime zdt = ZonedDateTime.of(2020, 7, 16, 0, 0, 0, 0, ZoneId.systemDefault());
long difference = getDifferenceInHours(zdt);
System.out.println(difference);
You shouldn't apply math to calculate date and time differences; there are many APIs out there doing the job pretty well.
I used ZonedDateTime
in the abovementioned code, because this takes possible DST changes into consideration. For example, in the Europe/Amsterdam timezone, between 29th March 2020, 00:00 and 05:00 are just 4 hours (instead of 5) due to the wall clock skipping an hour at two.
Presto: Difference in hours between two timestamps?
Yes. You are looking for date_diff
:
select date_diff('hour', now(), now() + interval '1' hour)
Output:
_col0 |
---|
1 |
How do I find the time difference between two datetime objects in python?
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
Subtracting the later time from the first time difference = later_time - first_time
creates a datetime object that only holds the difference.
In the example above it is 0 minutes, 8 seconds and 562000 microseconds.
How to get the time difference in hours between two Date.now()?
This is because the .getHours()
method of a Date
object simply returns the hour of the day that the object represents. It does not return the total number of hours since the epoch, and therefore you cannot simply subtract the two values to obtain a meaningful result.
You can achieve what you want with a simple subtraction and division:
const timeStart = new Date(1652836523287)
const timeEnd = new Date(1652848686623)
const hourDiff = (timeEnd - timeStart) / 1000 / 60 / 60
NOTE that I swapped the two timestamps since clearly 165284...
is after 165283...
.
Difference between two timestamps in hours
The internal representation of DATETIME is like in Excel, using the number of days elapsed. So to get the difference in hours is enough to compute the difference between the datetimes and multiply by 24 hours.
this is an example running on dax.do
DEFINE
TABLE T =
DATATABLE (
"DateTimeStart", DATETIME,
"DateTimeEnd", DATETIME,
{
{ "2021-02-09 19:30:02", "2021-02-10 22:00:02" }
}
)
EVALUATE
ADDCOLUMNS
(
T,
"Difference Hours", (T[DateTimeEnd] - T[DateTimeStart]) * 24
)
and this is the result
Calculate time difference between 2 timestamps in hours using R
The difference is a difftime
class built on top of numeric
. We could specify the units
in difftime
as seconds
and use seconds_to_period
from lubridate
library(lubridate)
df$differ_hrs<- as.numeric(difftime(df$End_Time, df$Start_Time,
units = "secs"))
out <- seconds_to_period(df$differ_hrs)
df$differ_HHMM <- sprintf('%02d:%02d', out@hour, out$minute)
NOTE: format
works only on Date
or Datetime class i.e. POSIXct, POSIXlt and not on numeric/difftime objects
data
df <- structure(list(ID = 1:3, Lat = c(-80.424, -80.114, -80.784),
Long = c(40.4242, 40.4131, 40.1142), Traffic = c(54L, 30L,
12L), Start_Time = structure(c(1514786400, 1514791800, 1514805300
), class = c("POSIXct", "POSIXt"), tzone = ""), End_Time = structure(c(1514787000,
1514792400, 1514809200), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA,
-3L), class = "data.frame")
Related Topics
Finding Out Current Index in Each Loop (Ruby)
Ruby on Rails - "Add 'Gem SQLite3'' to Your Gemfile"
How to Set Http_Referer When Testing in Rails
Select Arrays Between Date Ranges with Ruby
How to Check If a Given Directory Exists in Ruby
Error Installing Nokogiri on Bundle Install But Already Installed
Adding an Action to an Existing Controller (Ruby on Rails)
Rails on Windows Is So Slow (Rails -V Takes 4 Seconds)
Get the Value of an Instance Variable Given Its Name
In Ruby on Rails, After Send_File Method Delete the File from Server
What Does the * (Star) Mean in Ruby
Errno::Econnrefused: Connection Refused - Connect(2) for Action Mailer
Does Ruby Provide a Way to Do File.Read() with Specified Encoding
How to List Ruby Production Only Dependencies Using Gemfile.Lock and Lockfileparser Class