Calculating Difference in Time Between Two Time Objects

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).

Python - Calculate the difference between two datetime.time objects

To calculate the difference, you have to convert the datetime.time object to a datetime.datetime object. Then when you subtract, you get a timedelta object. In order to find out how many hours the timedelta object is, you have to find the total seconds and divide it by 3600.

# Create datetime objects for each time (a and b)
dateTimeA = datetime.datetime.combine(datetime.date.today(), a)
dateTimeB = datetime.datetime.combine(datetime.date.today(), b)
# Get the difference between datetimes (as timedelta)
dateTimeDifference = dateTimeA - dateTimeB
# Divide difference in seconds by number of seconds in hour (3600)
dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600

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 do you get the difference between two time objects in Python

The class datetime.time does not support object subtraction for the same reason it doesn't support object comparison, i.e. because its objects might not define their tzinfo attribute:

comparison of time to time, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised. If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base times are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset()). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a time object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.

You should use datetime.datetime which include both the date and the time.

If the two times refers to a single day, you can tell python that the date is today, with date.today() and combine the date with the time using datetime.combine.

Now that you have datetimes you can perform subtraction, this will return a datetime.timedelta instance, which the method total_seconds() that will return the number of seconds (it's a float that includes the microseconds information). So multiply by 106 and you get the microseconds.

from datetime import datetime, date, time

x = time(9, 30, 30, 0)
y = time(9, 30, 31, 100000)

diff = datetime.combine(date.today(), y) - datetime.combine(date.today(), x)
print diff.total_seconds() * (10 ** 6) # 1100000.0

You can also just use timedeltas:

from datetime import timedelta
x = timedelta(hours=9, minutes=30, seconds=30)
y = timedelta(hours=9, minutes=30, seconds=31, microseconds=100000)
print (y - x).total_seconds() * (10 ** 6) # 1100000.0

Calculating difference in time between two Time objects

This should work:

hours = ((created - updated) / 1.hour).round

Related question: Rails Time difference in hours

Calculating the time difference between two time stamp object - java

Manual time calculation:-

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :

  • 1000 milliseconds = 1 second
  • 60 seconds = 1 minute
  • 60 minutes = 1 hour
  • 24 hours = 1 day

Sample Example:-

package com.dps2.practice.dyuti;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

public static void main(String[] args) {

String dateStart = "08/11/2016 09:29:58";
String dateStop = "08/12/2016 10:31:48";

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null;
Date d2 = null;

try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

} catch (Exception e) {
e.printStackTrace();
}

}

}

How to calculate the time interval between two time strings

Yes, definitely datetime is what you need here. Specifically, the datetime.strptime() method, which parses a string into a datetime object.

from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime.

This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:

if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)

(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.

How do I check the difference, in seconds, between two dates?

if you want to compute differences between two known dates, use total_seconds like this:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0



Related Topics



Leave a reply



Submit