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 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 can i get the time difference between 2 time strings?
you need to import datetime module which contains method to convert string time to datetime object, once you have converted your time to datetime object , you can simply substract themtry using this,
import datetime
t1 = '11:19:04'
t2 = '11:19:07'
t1_time=datetime.datetime.strptime(t1,"%H:%M:%S")
t2_time=datetime.datetime.strptime(t2,"%H:%M:%S")
print t2_time-t1_time
0:00:03
Find difference between two time strings in Python
import datetime
a = "0628"
b = "0728"
timeA = datetime.datetime.strptime(a, "%H%M")
timeB = datetime.datetime.strptime(b, "%H%M")
print((timeB-timeA).total_seconds())
print(((timeB-timeA).total_seconds()/60.0))
Output:
3600.0
60.0
calculate time interval in minutes between two timestamps python
The easier way to do would be to convert datetime.strptime
object to datetime.timedelta
by simply subtracting two dates. Then applying simple arithmetic will give you the reuslt.
from datetime import datetime
time1= "2020-01-25T01:47:35.431Z"
time2="2020-01-25T02:02:57.500Z"
def to_minutes(td):
return td.days*1440 + td.seconds/60
def app_run2_min_diff(time1,time2):
time1 = datetime.strptime(time1,'%Y-%m-%dT%H:%M:%S.%fZ')
time2 = datetime.strptime(time2,'%Y-%m-%dT%H:%M:%S.%fZ')
time_diff = time2 - time1
min_dif = round(to_minutes(time_diff), 2)
return min_dif
The result of app_run2_min_diff(time1, time2)
will be:
15.37
JavaScript - difference between two time strings
This should get you started:
d1 = new Date(Date.parse("2017-05-02T10:45"));
d2 = new Date(Date.parse("2017-05-02T12:15"));
var getDuration = function(d1, d2) {
d3 = new Date(d2 - d1);
d0 = new Date(0);
return {
getHours: function(){
return d3.getHours() - d0.getHours();
},
getMinutes: function(){
return d3.getMinutes() - d0.getMinutes();
},
getMilliseconds: function() {
return d3.getMilliseconds() - d0.getMilliseconds();
},
toString: function(){
return this.getHours() + ":" +
this.getMinutes() + ":" +
this.getMilliseconds();
},
};
}
diff = getDuration(d1, d2);
console.log(diff.toString());
convert a time string to time
Please use the following way to subtract two time strings
from datetime import datetime
t1 = '10:33:26'
t2 = '11:15:49'
FMT = '%H:%M:%S' # time format
subtractedTime = datetime.strptime(t2, FMT) - datetime.strptime(t1, FMT)
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
).
Getting time difference between two time strings with Javascript
$(document).ready(function(){
var $time1 = $("#time1");
var $time2 = $("#time2");
var $diff = $("#totalTime");
function updateHours(){
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var diff = dtEnd - dtStart;
$diff.val(diff/1000);
}
$time1.add($time2).on("change, keyup", function(){
if($time1.val() && $time2.val()){
updateHours()
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="time1" type="text" placeholder="7:00 PM"/>
<input id="time2" type="text" placeholder="8:00 PM"/>
<input id="totalTime" readonly="readonly" />
Javascript: finding the time difference between two 'time' strings without involving date
Just do it as if you only had pen and paper:
- 12:45 => 12 × 60 + 45 = 765 minutes
- 08:30 => 8 × 60 + 30 = 510 minutes
- 765 - 510 = 255
- Integer division: 255 / 60 = 4 hours
- Remainer: 255 - 60 × 4 = 15 minutes
- Result: 04:15
You can parse from string using regular expressions:
var parts = "08:45".match(/^(\d+):(\d+)$/);
console.log(+parts[1], +parts[2], +parts[1] * 60 + +parts[2]);
Related Topics
How to Filter Only Printable Characters in a File on Bash (Linux) or Python
Multi Platform Portable Python
Running a Bash Script from Python
Executable Python Program with All Dependencies for Linux
Does Python Do Variable Interpolation Similar to "String #{Var}" in Ruby
How to Open (Read-Write) or Create a File with Truncation Allowed
Request Uac Elevation from Within a Python Script
How to Run Celery Workers by Superuser
Change Parent Shell's Environment from a Subprocess
Python Library for Linux Process Management
How to Install Pip on Arch Linux
How to Send Http Requests to Flask Server
Handling Spreadsheet Data Through the Clipboard in Gtk
What Does Asterisk * Mean in Python
Differencebetween Dict.Items() and Dict.Iteritems() in Python2