Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Time Difference

Tags:

python

time

at the start and end of my program, I have

from time import strftime print int(strftime("%Y-%m-%d %H:%M:%S")    Y1=int(strftime("%Y")) m1=int(strftime("%m")) d1=int(strftime("%d")) H1=int(strftime("%H")) M1=int(strftime("%M")) S1=int(strftime("%S"))   Y2=int(strftime("%Y")) m2=int(strftime("%m")) d2=int(strftime("%d")) H2=int(strftime("%H")) M2=int(strftime("%M")) S2=int(strftime("%S"))  print "Difference is:"+str(Y2-Y1)+":"+str(m2-m1)+":"+str(d2-d1)\           +" "+str(H2-H1)+":"+str(M2-M1)+":"+str(S2-S1) 

But when I tried to get the difference, I get syntax errors.... I am doing a few things wrong, but I'm not sure what is going on...

Basically, I just want to store a time in a variable at the start of my program, then store a 2nd time in a second variable near the end, then at the last bit of the program, compute the difference and display it. I am not trying to time a function speed. I am trying to log how long it took for a user to progress through some menus. What is the best way to do this?

like image 873
Brian Avatar asked Aug 06 '10 19:08

Brian


People also ask

How do you calculate time difference?

To calculate the time difference in minutes, you need to multiply the resulting value by the total number of minutes in a day (which is 1440 or 24*60). Suppose you have a data set as shown below and you want to calculate the total number of minutes elapsed between the start and the end date.

How do you calculate time difference between minutes?

To get the time difference in a single time unit (hours ,minutes or seconds), you can perform the following calculations. Total minutes between two times: To calculate the minutes between two times, multiply the time difference by 1440, which is the number of minutes in one day (24 hours * 60 minutes = 1440).

How do I calculate the time difference between two times in Excel?

You use the subtraction operator (-) to find the difference between times, and then do either of the following: Apply a custom format code to the cell by doing the following: Select the cell. On the Home tab, in the Number group, click the arrow next to the General box, and then click More Number Formats.


1 Answers

The datetime module will do all the work for you:

>>> import datetime >>> a = datetime.datetime.now() >>> # ...wait a while... >>> b = datetime.datetime.now() >>> print(b-a) 0:03:43.984000 

If you don't want to display the microseconds, just use (as gnibbler suggested):

>>> a = datetime.datetime.now().replace(microsecond=0) >>> b = datetime.datetime.now().replace(microsecond=0) >>> print(b-a) 0:03:43 
like image 95
Tim Pietzcker Avatar answered Oct 04 '22 03:10

Tim Pietzcker