Calculate time difference only considering hours - python

I want to calculate the time difference in hour not considering the date.
For example I want the difference between 22:00:00 and 01:00:00 to be 3.
The code I got so far:
time1 = datetime.strptime("22:00:00", '%H:%M:%S')
time2 = datetime.strptime("01:00:00", '%H:%M:%S')
res = time1-time2
print(res)
The output I got: 21:00:00
The output I want: 3

You cannot extract the hours directly from the resulting timedelta object, as they keep fraction-of-day as seconds, so a simple workaround is to take the seconds and calculate the hours from there.
Also note that you want to subtract time1 to time2, otherwise you will get 21 hours:
(time2 - time1).seconds/3600
# 3

Related

Comparing two times without date in Python?

Let's assume I have two times with no date as shown below.
>>> time_1 = datetime.datetime.strptime("05:30", "%H:%M")
>>> time_2 = datetime.datetime.strptime("05:00", "%H:%M")
To compare these two, I can simply do this:
>>> time_1<= time_2
False
Now, for this example when I know 03:30 happens before "23:30", I get False as well.
>>> time_1=datetime.datetime.strptime("23:30", "%H:%M")
>>> time_2=datetime.datetime.strptime("03:30", "%H:%M")
>>> time_1<= time_2
False
I am trying to know if there is any way to handle this situations?
if time2 < time1:
time2 += datetime.timedelta(days=1)
assuming the second time is always the next day if it is less than the first time
assuming the time strings represent a time series, i.e. they appear in chronological order, one can derive datetime by adding as duration to an arbitrary date (I have to revise my comment #Selcuk ...). Something like
from datetime import datetime, time, timedelta
# assuming the "cyclic time" looks similar to this:
cycletimes = ["05:00", "05:30", "23:30", "03:30"]
# we can convert to timedelta;
# to_td converts HH:MM string to timedelta
to_td = lambda s: timedelta(hours=int(s.split(':')[0]), minutes=int(s.split(':')[1]))
durations = list(map(to_td, cycletimes))
# take an arbitrary date
refdate = datetime.combine(datetime.today().date(), time.min)
# what we want is datetime; we can already set the first entry
datetimes = [refdate+durations[0]]
# now we iterate over cycle times; if the next value is smaller, we add a day to refdate
for t0, t1, d in zip(cycletimes[:-1], cycletimes[1:], durations[1:]):
if t1 < t0:
refdate += timedelta(1)
datetimes.append(refdate+d)
print(f"{datetimes[0]} <= {datetimes[1]} -> {datetimes[0] <= datetimes[1]}")
# 2021-08-26 05:00:00 <= 2021-08-26 05:30:00 -> True
print(f"{datetimes[2]} <= {datetimes[3]} -> {datetimes[2] <= datetimes[3]}")
# 2021-08-26 23:30:00 <= 2021-08-27 03:30:00 -> True
Now for example "23:30" appears before "03:30", not after as if you'd only compare time. Side note, pure Python is great to illustrate the logic here; in the "real world" however I'd suggest to have a look at the pandas library for such a task.

Why is the diff of two datetime objects so?

datetime1 = '2020-08-19 10:13:19'
datetime2 = '2020-08-19 19:00:00'
diff = datetime1 - datetime2
The diff is a timedelta object, with:
diff.days = -1
diff.seconds = 54766 = 15.22 hours
There are only about 9 hours diff between the two datetimes. Why does it show the number of days is '1' and 15.22 hours? How to understand the diff of two datetimes?
If you subtract the earlier datetime from the later datetime, you get a positive timedelta, as one would expect.
The other way around, you get a negative timedelata in the unusual format.
But when you calculate -1 day + 15 hours = -24 hours + 15 hours = -9 hours, the result is correct.
Of course, doing this calculation manually is not what we want.
So, either avoid subtracting a later datetime from an earlier datetime:
# to get an absolute timedelta
if datetime2 > datetime1:
print(datetime2 - datetime1)
else:
print(datetime1 - datetime2)
Or use .total_seconds():
print((datetime1 - datetime2).total_seconds())
-31601.0
print((datetime2 - datetime1).total_seconds())
31601.0
In this example, the difference between two datetime objects has a negative number of days, and a positive number of hours.
import datetime
datetime1 = datetime.datetime.fromisoformat('2020-08-19 10:13:19')
datetime2 = datetime.datetime.fromisoformat('2020-08-19 19:00:00')
print(datetime1 - datetime2)
-1 day, 15:13:19
# divide by timedelta() (with argument of hours, minutes, seconds, etc.
print((datetime1 - datetime2) / datetime.timedelta(hours=1)) # in hours
-8.778055555555556
Here is an interesting interview with the core developer who maintains date / time in CPython: https://talkpython.fm/episodes/show/271/unlock-the-mysteries-of-time-pythons-datetime-that-is
UPDATE
You can calculate time difference in minutes, or days, or other units, by supplying a different parameter to .timedelta():
print((datetime1 - datetime2) / datetime.timedelta(minutes=1)) # in minutes
-526.68
print((datetime1 - datetime2) / datetime.timedelta(days=1)) # in days
-0.3658

How to get a time interval between two strings?

I have 2 times stored in separate strings in the form of H:M I need to get the difference between these two and be able to tell how much minutes it equals to. I was trying datetime and timedelta, but I'm only a beginner and I don't really understand how that works. I'm getting attribute errors everytime.
So I have a and b times, and I have to get their difference in minutes.
E.G. if a = 14:08 and b= 14:50 the difference should be 42
How do I do that in python in the simplest way possible? also, in what formats do I need to use for each step?
I assume the difference is 42, not 4 (since there are 42 minutes between 14:08 and 14:50).
If the times always contains of a 5 character length string, than it's reasonably easy.
time1 = '14:08'
time2 = '15:03'
hours = int(time2[:2]) - int(time1[:2])
mins = int(time2[3:]) - int(time1[3:])
print(hours)
print(mins)
print(hours * 60 + mins)
Prints:
1
-5
55
hours will be the integer value of the left two digits [:1] subtraction of the second and first time
minutes will be the integer value of the right two digits [3:] subtraction of the second and first time
This prints 55 ... with your values it prints out 42 (the above example is to show it also works when moving over a whole hour.
You can use datetime.strptime
also the difference is 42 not 4 50-8==42 I assume that was a typo
from datetime import datetime
a,b = "14:08", "14:50"
#convert to datetime
time_a = datetime.strptime(a, "%H:%M")
time_b = datetime.strptime(b, "%H:%M")
#get timedelta from the difference of the two datetimes
delta = time_b - time_a
#get the minutes elapsed
minutes = (delta.seconds//60)%60
print(minutes)
#42
You can get the difference between the datetime.timedelta objects created from the given time strings a and b by subtracting the former from the latter, and use the total_seconds method to obtain the time interval in seconds, with which you can convert to minutes by dividing it by 60:
from datetime import timedelta
from operator import sub
sub(*(timedelta(**dict(zip(('hours', 'minutes'), map(int, t.split(':'))))) for t in (b, a))).total_seconds() // 60
So that given a = '29:50' and b = '30:08', this returns:
18.0

How to subtract military time between days with datetime module

I am working on a time lapse program and I would like to be able to pause overnight over multiple days. I am using military time and when I try say 18:00:00 as pause start and 08:00:00 as pause end I get a negative number. I could probably take the difference between 24:00:00 and 18:00:00 and 0:00:00 and 08:00:00 and add them to get the answer, but I'm wondering if there is something I'm missing in the datetime module that would allow me to do this?
from datetime import datetime
pause_start=input('Enter pause start time as 24 hrs (hh:mm:ss): ')
pause_end=input('Enter pause end time as 24 hrs (hh:mm:ss): ')
pause_start=datetime.strptime(pause_start, '%H:%M:%S')
pause_end=datetime.strptime(pause_end, '%H:%M:%S')
total_pause_time=(pause_end-pause_start).total_seconds()
print(total_pause_time)
input:18:00:00
input:08:00:00
output:-36000.0
I tried an input of 25:00:00 and received an error saying time data did not match format '%H:%M:%S' therefore I believe it is being read correctly as military time.
What you are missing, is that you are calculating with times on the same day. So you are subtracting the later time from the earlier time which gives a negative result. I see two solutions:
Add 24 hours to the final result to get the correct offset.
Create datetime objects so that 18:00:00 is today and 08:00:00 is tomorrow morning. Then subtract the dates.

Difference between 2 dates in minutes

can you tell me how can I calculate difference between 2 dates and get a result in minutes.
For exmpl. : date1 - 2016/07/13, 14:25:00
date2 - 2016/07/14, 10:00:00
If my format Is maybe different from format that python use(while I was searching for answer I saw a several formats) feel free to adapt it.
import datetime
from datetime import timedelta
def date(dd,vd,dp,vp):
datetimeFormat = '%Y/%m/%d %H:%M:%S'
time1 = ('{0} {1}'.format(dd,vd))
time2 = ('{0} {1}'.format(dp,vp))
timedelta = datetime.datetime.strptime(time2, datetimeFormat) - datetime.datetime.strptime(time1,datetimeFormat)
print (timedelta)
def main():
date1,time1='2016/07/13','14:25:00'
date2,time2='2016/07/14','10:00:00'
date(date1,time1,date2,time2)
if name=='main':
main()
If you compile it you will get something like 19hrs which is incorrect. Also I need result in minutes.

Categories

Resources