This question already has answers here:
How to calculate the time interval between two time strings
(15 answers)
Closed 1 year ago.
i have two Datetimes for worker ( start work time , end work time) . im just trying to subtract the end work time from start work time
starttime = "23:51:26"
endtime = "04:10:11"
FMT = '%H:%M:%S'
tdelta = datetime.strptime(endtime, FMT) - datetime.strptime(starttime, FMT)
print(tdelta)
Result
-1 day, 4:18:45
I want the result to be 4:18:45
any help ? thanks
Here your snippet!
from datetime import datetime, timedelta
starttime = "04:10:11"
endtime = "23:51:26"
FMT = '%H:%M:%S'
t1 = datetime.strptime(starttime, FMT)
t2 = datetime.strptime(endtime, FMT)
tdelta = (t1 - t2) * (1 - 2 * (t1 < t2))
print(tdelta)
Related
I would like to calculate the time difference between two 24-hour time values, containing only the hour, minute, and second values. Then, I would like to split up the time difference into the hour, minute, and seconds values, and output them as three different variables.
For example, my desired output would be:
time1 = '10:33:26'
time2 = '17:25:39'
Hours: 6
Minutes: 52
Seconds: 13
Because 17:25:39 is 6 hours, 52 minutes, and 13 seconds after 10:33:26.
I have tried the following code:
from datetime import datetime
s1 = '10:33:26'
s2 = '17:25:39'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print(tdelta)
It correctly outputs 6:52:13, but I don't know how to split up the 6, 52, and 13 into three different variables.
You probably want to do the numeric calculation yourself directly from the total_seconds(), rather than relying on back-parsing the result of the string conversion (intended for human-readable output). For example:
from datetime import datetime
s1 = '10:33:26'
s2 = '17:25:39'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
ts = int(tdelta.total_seconds())
secs = ts % 60
mins = (ts // 60) % 60
hours = (ts // 3600)
print(hours, mins, secs)
You can perform numeric computation by using timedelta.
time1 = datetime.timedelta(hours=10, minutes=33,seconds=26)
time2 = datetime.timedelta(hours=17, minutes=25,seconds=39)
time_diff = time2 - time1
hour, min, sec = str(time_diff ).split(':')
print(hour, min, sec)
You can convert the output to a string and then use the split() method. For example:
str(tdelta).split(':')
Will output:
['6', '52', '13']
Then you can simply loop through the outputted list.
Start time is in format datetime with :
YYYY-MM-DDTHH:MM:SS.SSSZ (e.g., 2004-08-04T19:09:02.768Z)
My code
starttime = item['ListingDetails']['StartTime']
present_date = datetime.now() - timedelta(days=2)
startdate = datetime.strptime(starttime, 'WhichFormat')
if startdate.date() < present_date.date():
print('Relisting item :', str(itemid), starttime)
Is throwing the exception because i dont know which was the real format.
Goal is to see if start time is 2 days ago.
I.E If item was relisted 2 days ago + then relist it now
If I understand correctly, you can use dateutil.parser:
import dateutil.parser
starttime = item['ListingDetails']['StartTime']
present_date = datetime.now() - timedelta(days=2)
startdate = dateutil.parser.parse('2004-08-04T19:09:02.768Z')
if startdate.date() < present_date.date():
print('Relisting item :', str(itemid), starttime)
I'm trying to find the difference between the StartTime and LastTime (minutes) in this DataFrame:
StartTime LastTime
1 00:02:05 00:02:05
2 00:07:05 00:07:05
3 00:12:06 00:12:06
4 00:17:06 00:17:06
When I run the following code on the data
from datetime import datetime
date_format = "%H:%M.%S"
# You could also pass datetime.time object in this part and convert it to string.
time_start = str(UDP_interval['StartTime'])
time_end = str(UDP_interval['LastTime'])
# Then get the difference here.
diff = datetime.strptime(time_end, date_format) -
datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
I get this error:
dtype: object' does not match format '%H:%M:%S'
You should probably just use:
t_start = list(map(int, str(UDP_interval['StartTime']).split(':'))) # get hours, minutes, seconds separately
t_end = list(map(int, str(UDP_interval['LastTime']).split(':')))
diff = (t_start[0] - t_end[0]) + (t_start[1] - t_start[1]) / 60 + (t_start[2] - t_start[2]) / 3600
Question How do I print out the remaining hours of overtime
Example: I have to be at work for 8 hours, and if my time goes over 8 hours as shown in OUTPUT then I just wanna have the 00:03:00 printed out..
Meaning that I have 3 min overtime that day.
from datetime import datetime
s1 = '07:15:00'
s2 = '16:18:00'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print(tdelta)
OUTPUT
9:03:00
Subtract the length of the working day with a timedelta object...
from datetime import datetime, timedelta
s1 = '07:15:00'
s2 = '16:18:00'
FMT = '%H:%M:%S'
work_time = timedelta(hours=8)
lunch_time = timedelta(hours=1)
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT) - work_time - lunch_time
print(tdelta)
Output:
0:03:00
You need to subtract the length of the working day (and it would appear an hour to account for breaks) from tdelta to determine the excess.
I want to calculate difference between two time in hours using django in sql db the time are stored in timefield.
I tried this:
def DesigInfo(request): # attendance summary
emplist = models.staff.objects.values('empId', 'name')
fDate = request.POST.get('fromDate')
tDate = request.POST.get('toDate')
if request.GET.get('empId_id'):
sel = attendance.objects.filter(empId_id=request.GET.get('empId_id'),)
for i in sel:
# print i.
# print i.outTime
# print i.inTime.hour,i.inTime.minute,i.inTime.second - i.outTime.hour,i.outTime.minute,i.outTime.second
ss = i.inTime.hour
ss1 = 12 - ss
mm = i.outTime.hour
mm1 = (12 + mm) - 12
print ss1 + mm1
Since i.inTime and i.outTime are time objects you cannot simply subtract them. A good approach is to convert them to datetime adding the date part (use today() but it is irrelevant to the difference), then subtract obtaining a timedelta object.
delta = datetime.combine(date.today(), i.outTime) - datetime.combine(date.today(), i.inTime)
(Look here: subtract two times in python)
Then if you want to express delta in hours:
delta_hours = delta.days * 24 + delta.seconds / 3600.0
A timedelta object has 3 properties representing 3 different resolutions for time differences (days, seconds and microseconds). In the last expression I avoided to add the microseconds but I suppose it is not relevant in your case. If it is also add delta.microseconds / 3600000000.0
Note that simply dividing seconds by 3600 would have returned only the integer part of hours avoiding fractions. It depends on your business rules how to round it up (round, floor, ceil or leave the fractional part as I did)
Using datetime objects: https://docs.python.org/2/library/datetime.html
A good stack overflow post on the topic How to get current time in Python
from datetime import datetime
now = datetime.now()
# wait some time
then = ... some time
# diff is a datetime.timedelta instance
diff = then - now
diff_hours = diff.seconds / 3600
You might want to play with this codes:
from datetime import datetime
#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"
#convert string to actual date and time
time1 = datetime.strptime('8-01-2008 00:00:00', date_format)
time2 = datetime.strptime('8-02-2008 01:30:00', date_format)
#find the difference between two dates
diff = time2 - time1
''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')
#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');
''' now print only the time difference '''
''' between two times (date is ignored) '''
print ('\nTime difference between two times (date is not considered)')
#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600
hours = (diff.seconds) / 3600
print (str(hours) + ' Hours')
#same for minutes just divide the seconds by 60
minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')
#to print seconds, you know already ;)
print (str(diff.seconds) + ' secs')
The easiest way through I achieve is the comment of Zac given above. I was using relativedelta like this
from dateutil import relativedelta
difference = relativedelta.relativedelta( date1, date2)
no_of_hours = difference.hours
but it did not give me correct result when the days changes. So, I used the approach expressed above:
no_of_hours = (difference.days * 24) + (difference.seconds / 3600)
Please note that you will be getting negative value if date2 is greater than date1. So, you need to swipe the position of date variables in relativedelta.