Get Delta/Elapse time in Python with datetime

Do you remember when we were young, we used hours to time notions, “I’ll be there in an hour”, “It takes about half-hour”, “My mail will reach next week”. Oh my, week?! Well it did happen. Once upon a time.

we evolved to be impatient

We were talking about getting time with time python module which be fine for human. Now human need to keep up with machine, let’s keep up with them then, we are talking with milliseconds and microseconds now, we will use datetime.

[python]
import datetime

>>> datetime.datetime.now()
datetime.datetime(2012, 2, 17, 20, 29, 53, 567000)
[/python]

uh, …, I will change it. Too much typing.

[python]
from datetime import datetime

startTime = datetime.now()

# do something fast! faster!

elapsedTime = datetime.now() – startTime
print elapsedTime.microseconds
[/python]

Notice on microseconds, because Pyhton give in microseconds we can simply convert it to milliseconds with * 1000

What if things might takes in minutes, hours? for this we can utilize total_seconds(), divmod function, and print formating and come up with

[python smarttabs=”true”]
from datetime import datetime

startTime = datetime.now()

# do something fast! faster!

elapsedTime = datetime.now() – startTime

totSecs = elapsedTime.total_seconds()
theHours, reminder = divmod(totSecs, 3600)
theMins, reminder = divmod(reminder, 60)
theSecs, theMicroSec = divmod(reminder, 1)

print "action taken in %02d:%02d:%02d.%d" %
(theHours, theMins, theSecs, theMicroSec)
[/python]

we can change microseconds to milliseconds depending on needs, but that’s the idea.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s