What is the simplest way to find the difference between 2 times in python?

I have 2 time values which have the type datetime.time. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type datetime.datetime but not for datetime.time. So what is the best way to do this?

Asked by: Roman324 | Posted: 01-10-2021

Answer 1

Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using datetime.datetime.combine, then subtracting:

>>> import datetime
>>> t1 = datetime.time(2,3,4)
>>> t2 = datetime.time(18,20,59)
>>> dummydate = datetime.date(2000,1,1)
>>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1)
datetime.timedelta(0, 58675)

Answered by: Rafael264 | Posted: 02-11-2021

Answer 2

You could transform both into timedelta objects and subtract these from each other, which will take care to of the carry-overs. For example:

>>> import datetime as dt
>>> t1 = dt.time(23, 5, 5, 5)
>>> t2 = dt.time(10, 5, 5, 5)
>>> dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond)
>>> dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond)
>>>  print(dt1-dt2)
>>> print(dt2-dt1)
-1 day, 11:00:00
>>> print(abs(dt2-dt1))

Negative timedelta objects in Python get a negative day field, with the other fields positive. You could check beforehand: comparison works on both time objects and timedelta objects:

>>> dt2 < dt1
>>> t2 < t1

Answered by: Melanie120 | Posted: 02-11-2021

Answer 3

Python has pytz (http://pytz.sourceforge.net) module which can be used for arithmetic of 'time' objects. It takes care of DST offsets as well. The above page has a number of examples that illustrate the usage of pytz.

Answered by: Richard320 | Posted: 02-11-2021

Answer 4

It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know this isn't an answer directly, but maybe someone with more python experience than me can take this a little further. For more info, see this: http://bugs.python.org/issue3250

Answered by: Stuart208 | Posted: 02-11-2021

Answer 5

Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.

One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.

t1, t2 = datetime.time(...), datetime.time(...)

t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond
t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond

delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])

It's a little lame, but it works.

Answered by: Daisy777 | Posted: 02-11-2021

Answer 6

Retrieve the times in milliseconds and then do the subtraction.

Answered by: Brianna845 | Posted: 02-11-2021

Answer 7

Environment.TickCount seems to work well if you need something quick.

int start = Environment.TickCount


int elapsedtime = Environment.TickCount - start


Answered by: Chester626 | Posted: 02-11-2021

Similar questions

datetime - Date difference in minutes in Python

How do I calculate the difference in time in minutes for the following timestamp in Python? 2010-01-01 17:31:22 2010-01-03 17:31:22

datetime - python: difference of two timedate strings

I have two date strings (taken from user input and can vary greatly) s1 = '2011:10:01:10:30:00' s2 = '2011:10:01:11:15:00' I wish to find the difference between the two as minutes. How should I proceed to tackle this ?

Difference between Python datetime vs time modules

I am trying to figure out the differences between the datetime and time modules, and what each should be used for. I know that datetime provides both dates and time. What is the use of the time module? Examples would be appreciated and differences concerning timezones would especially be of interest.

How to find difference in time from current date and an query datetime in python?

+---------+---------------------+---------------------+ | area_id | date_1 | date_2 | +---------+---------------------+---------------------+ | NULL | 2012-06-28 10:09:18 | 2012-06-28 10:15:48 | | 18 | 2012-06-28 10:15:48 | 2012-06-28 10:20:26 | | 21 | 2012-06-28 10:20:26 | 2012-06-28 10:32:51 | | 3 | 2012-06-28 10:32:51 | 2012-06-28 10:50:27 | | 21 | 2012-06-28 10:...

python - Get new datetime object according to timezone difference

Here is my code &gt;&gt;&gt;from datetime import datetime &gt;&gt;&gt;from dateutil import tz &gt;&gt;&gt;current_time = datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta')) &gt;&gt;&gt;2013-05-12 17:11:36.362000+05:30 i don't want offset-aware i want to add time difference to my current time so the time will be &gt;&gt;&gt;2013-05-12 22:41:36.362000 ...

datetime - Difference between two times python

I can't get this working. I'm tired of searching, but I can't find anything. I don't have a date, I only have time (01:45, 05:30). I'm only using the library 'Time', currently I have the code above, which gives me the minutes between the hours. But this is not enough. In this example, the final result should be: 225 minutes 3 hours (rounded down) hour_beg = '01:45' hour_cl...

datetime difference in python

for proc in psutil.process_iter(): if proc.name == "monit": current_time = time.localtime() proc_start_time = time.localtime(proc.create_time) print (current_time - proc_start_time).seconds I am not able to find difference between two datetimes. Can't subtract them give Error - TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.st...

datetime - Trying to find difference in days between user's date of birth and now, in Python

I am learning python(beginner) and have been set a task to write a program to find difference in days between user's date of birth and now, in Python. I know how to work out the time now (datetime.now) and how to ask the user to input something(raw_input). However, these answers are in different formats, so there is no way to subtract one from another. Is there a way of converting them to the same format, or would slicing...

python - Why is there 1 hour difference between gmtime and utcnow datetime?

If I do: &gt;&gt;&gt; print datetime.fromtimestamp(time.mktime(time.gmtime())) - datetime.utcnow() it prints: 0:59:59.618000 Why would the utcnow() give 4 hours offset from my local time and gmtime() 5 hours? This prints -5 and: print int(-time.timezone/60/60) Isn't all this supposed to be UTC time?

datetime - How do you get the difference between two time objects in Python

I have two datetime.time objects in Python, e.g., &gt;&gt;&gt; x = datetime.time(9,30,30,0) &gt;&gt;&gt; y = datetime.time(9,30,31,100000) However, when I do (y-x) as what I would do for datetime.datetime object, I got the following error: Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; y-x TypeError: unsupported operand type(s...

algorithm - Average difference between dates in Python

I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?

c# - Text difference algorithm

I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not. The implementation can be in c# or python. Thanks.

Is there any difference between "string" and 'string' in Python?

This question already has answers here:

What is the difference between Ruby and Python versions of"self"?

I've done some Python but have just now starting to use Ruby I could use a good explanation of the difference between "self" in these two languages. Obvious on first glance: Self is not a keyword in Python, but there is a "self-like" value no matter what you call it. Python methods receive self as an explicit argument, whereas Ruby does not. Ruby sometimes has methods explicitly d...

python - What's the difference between all of the os.popen() methods?

I was looking at the Python documentation and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include stderr while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very wel...

datetime - Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?

I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post. Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. Can't I just get in whatever time unit I ...

Difference between the use of double quote and quotes in python

This question already has answers here:

python - How to tell the difference between an iterator and an iterable?

In Python the interface of an iterable is a subset of the iterator interface. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable __iter__ returns a new iterator object and not just self. How ...

Difference between class (Python) and struct (C)

I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference?

syntax - What's the difference between "2*2" and "2**2" in Python?

What is the difference between the following statements? Statement 1: var=2**2*3 Statement 2: var2=2*2*3 I see no difference. This raises the following question. Why is Statement 1 used if we can use Statement 2?

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python