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.
Related
Example:
9:43 - 17:27 - how many hours and minutes elapsed between those times ?
Here is one approach to get the number of total minutes:
from datetime import datetime
s = '9:30 - 14:00 ; 14:30 - 16:30'
sum(((b-a).total_seconds()/60 for x in s.split(' ; ')
for a,b in [list(map(lambda t: datetime.strptime(t, '%H:%M'), x.split(' - ')))]))
Output: 390.0
If you know that the time periods will never span midnight, then you could simply split the time strings with time.split(":") and do the math yourself with the hours and minutes.
However, the correct solution would be to import the datetime module and calculate the timedelta.
This example could be condensed. I intentionally made it verbose without knowing exactly how you're getting your inputs:
from datetime import datetime
times = [
"9:30",
"14:00",
"14:30",
"16:30"
]
#Just using today's date to fill in the values with assumption all times are on the same day.
year = 2022
month = 6
day = 9
date_times = []
for time in times:
split_time = time.split(":")
hour = split_time[0]
minutes = split_time[1]
timestamp = datetime.datetime.today(year=year, month=month, day=day, hour=hour, min=minutes)
date_times.append(timestamp)
total_seconds = 0
for i in range(1, len(date_times), 2):
delta = date_times[i] - date_times[i-1] # The timedelta object returned will have days, seconds, milliseconds
total_seconds += delta.days * 86400 + delta.seconds
hours = total_seconds // 3600 # Integer division
minutes = round((total_seconds % 3600) / 60) # Change depending on if you want to round to nearest, or always up or down.
My expertise lack when it comes to understanding this time format. I am guessing the ,XXX is XXX/1000 of a second?
Nevertheless I am trying to add a text files that contains time stamp like these and sum up the total.
Below is an example,
00:03:33,950
00:03:34,590
This is what I have so far but I'm not sure how to add up the last part
Hours = s.split(":")[0]
Minutes = s.split(":")[1]
Seconds = (s.split(":")[2]).split(",")[0]
Total_seconds = (Hours * 3600) + (Minutes * 60) + (Seconds)
Total_Time = str(datetime.timedelta(seconds=Total_seconds))
Reed this documentation about time.strftime() format
For example
from time import gmtime, strftime
strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
--'Thu, 28 Jun 2001 14:17:15 +0000'--
Actually, you're halfway there.
All you have to do is to to convert your strs into int and pass them as parameters to the appropriate timedelta keywords.
from datetime import timedelta
Hours = int(s.split(":")[0])
Minutes = int(s.split(":")[1])
Seconds = int((s.split(":")[2]).split(",")[0])
Milliseconds = int((s.split(":")[2]).split(",")[1])
duration = timedelta(hours=Hours, minutes=Minutes, seconds=Seconds, milliseconds=Milliseconds)
After adding all the durations you need, str() the final timedelta object.
>>> durations_1 = timedelta(hours=2,milliseconds=750)
>>> durations_2 = timedelta(milliseconds=251)
>>> durations_sum = durations_1 + durations_2
>>> str(durations_sum)
'2:00:01.001000'
>>> str(durations_sum).replace('.',',')
'2:00:01,001000'
I would like to measure the execution time of some piece of code in days, hours, minutes and seconds.
This is what I have so far:
import time
start_time = time.time()
# some code
elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time))
print(f"Took: {elapsed}")
The problem is that if the code that I am measuring takes longer than 24h, the time displayed overflows and starts from zero again. I would like something like this:
# Example: 12 hours and 34 minutes should be printed as
> Took: 12:34:00
# Example: 26 hours and 3 minutes should be printed as
> Took: 1:02:03:00
You could use datetime:
from datetime import datetime as dt
start = dt.fromtimestamp(1588432670)
end = dt.now()
elapsed=end-start
print("Took: %02d:%02d:%02d:%02d" % (elapsed.days, elapsed.seconds // 3600, elapsed.seconds // 60 % 60, elapsed.seconds % 60))
Output:
Took: 33:00:21:49
The result of time.gmtime(time.time() - start_time) is not what you seem to think it is. Instead of being a duration of time it is a point in time. Let me explain.
The result of time.time() is the number of seconds since January 1, 1970, 00:00:00 (UTC) at the time of calling. Therefore, the statement time.time() - start_time will produce the number of seconds between the two calls. So far so good. However, the time.gmtime function is interpreting this duration as the number of seconds since January 1, 1970, 00:00:00 (UTC) and formatting the time accordingly. What you are seeing then is the time portion of the date January 1, 1970, 12:34:00 (UTC).
I suggest you either use the datetime.timedelta object and format using that, or as others have suggested, output the duration in seconds or milliseconds.
If you want to format this number yourself, you could use something like this:
def format_duration(duration):
mapping = [
('s', 60),
('m', 60),
('h', 24),
]
duration = int(duration)
result = []
for symbol, max_amount in mapping:
amount = duration % max_amount
result.append(f'{amount}{symbol}')
duration //= max_amount
if duration == 0:
break
if duration:
result.append(f'{duration}d')
return ' '.join(reversed(result))
You should try this:
import time
start_time = time.time()
...
elapsed_time = time.time() - start_time
days = 0
if elapsed_time >= 86400:
days = int(elapsed_time / 86400)
elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time))
if days == 0:
print(f"Took: {elapsed}")
else:
print(f"Took: {days}:{eplased}")
Time types can only include hours and less units. You should use datetime instead of time as follows:
from datetime import datetime
start_time = datetime.now()
# some code
elapsed = datetime.now() - start_time)
print(f"Took: {elapsed}")
Example usage of Datetime:
from datetime import datetime
d1 = datetime(2013,9,1,5,5,4)
d2 = datetime(2013,1,13,3,2,1)
result1 = d1-d2
print ('{} between {} and {}'.format(result1, d1, d2))
This produces following output:
231 days, 2:03:03 between 2013-09-01 05:05:04 and 2013-01-13 03:02:01
Try using timeit:
import timeit
timeit.timeit(<callable function>, number = 100)
Here timeit will call callable function number times and give you the average runtime.
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.
How can I parse the time 004:32:55 into a datetime object? This:
datetime.strptime("004:32:55", "%H:%M:%S")
doesn't work becaush %H expects two digits. Any way to add the third digit?
Three options :
s = "004:32:55"
from datetime import datetime
datetime.strptime(s[1:], "%H:%M:%S") # from second 0 to the end
datetime.strptime(s, "0%H:%M:%S") # add 0 in formatting
from dateutil import parser # use dateutil
parser.parse(s)
There are 24 hours in a day so you can divide and get the modulus to figure out how many days and hours are in the time, then subtract the days, this needs some tweaking will get you started.
s = "04:32:55"
s = s.split(":",1)
hours, days = divmod(int(s[0]),24)
new_time = "{}:{}".format(hours,s[1])
past = datetime.now() - timedelta(days=days)
final = "{} {}".format(past.date().isoformat(),new_time)
print datetime.strptime(final,"%Y-%m-%d %H:%M:%S")
I chose a more pragmatic approach in the end and converted the time stamp to seconds:
hours = (0 if time_string.split(":")[0] == "000" else int(time_string.split(":")[0].lstrip("0")) * 3600)
mins = (0 if time_string.split(":")[1] == "00" else int(time_string.split(":")[1].lstrip("0")) * 60)
secs = (0 if time_string.split(":")[2] == "00" else int(time_string.split(":")[2].lstrip("0")))
return hours + mins + secs
Converting back to hours, minutes, and seconds is easy with datetime.timedelta(seconds=123).
EDIT:
A better solution (thanks to Ben):
hours = int(time_string.split(":")[0]) * 3600
mins = int(time_string.split(":")[1]) * 60
secs = int(time_string.split(":")[2])
return hours + mins + secs