Title: Calculating time difference in python
Tags: python;datetime;duration;timedelta
Question: I want to make a code in python to find out the duration an employee had worked by taking two inputs.
input1 will be the time when the employee arrived at work, in hh:mm format.
input2 will be the time when the employee left work, in hh:mm format.
I want to calculate the duration an employee worked in hh:mm format when I subtract input1 from input2.
Please help in making this code.
Comment: What have you tried so far? What isn’t working about the approaches you’ve taken?


Here is another answer: There is no timedelta attribute for time objects.
You can use a datetime object first, then do:
difference = datetime1 - datetime2
The, finally, do:
print(difference.strftime('%H:%M')
Alternatively, if you are only allowed to use time input/object, you can do:
import datetime
# Time in example
a = datetime.time(9, 30)
# Time out example
b = datetime.time(17, 45)
hours = abs(int(b.strftime('%H')) - int(a.strftime('%H')))
minutes = abs(int(b.strftime('%M')) - int(a.strftime('%M')))
time_difference = datetime.time(hours, minutes)
print(time_difference)
Comment for this answer: [timedelta](https://docs.python.org/3/library/datetime.html#timedelta-objects) has no method strftime either

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:06/20/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><datetime><duration><timedelta>', 'Title': 'Calculating time difference in python', 'ViewCount': 45, 'id': 62488895, 'user_AboutMe': None, 'user_AccountId': 18892310.0, 'user_DisplayName': 'Sumeet Dhancholia', 'user_Reputation': 1.0, 'user_Views': 1.0, 'user_id': 13782329.0}}