#Python – Working with dates đź“…, formats, and subtract for time difference. Timedelta type rocks!

Buy Me A Coffee

Hi !

I’m switching from C#9 to Python to write this down, so I avoid to search and write this from scratch again and again. My scenario includes very simple operations with dates,

  • Tag a start date time
  • Do some process, I’ll fake it with random sleep
  • Tag a end date time
  • Calculate the different between them
  • Process and show the difference with a specific format

For this I’ll use the datetime type, and a cool feature using datetime is that we can directly substract 2 dates. In example:

start = datetime.datetime.utcnow()
time.sleep(10)
end = datetime.datetime.utcnow()

delta = end - start

In this code 👆, the delta variable is a timedelta type. This is not a standard datetime, in C# we know this as TimeSpan. We can access the internal values, and get some details around hours, minutes, seconds and millisecons:

def get_timedelta_values(delta):
    # Get the hours, minutes, seconds and milliseconds
    millis           = round(delta.microseconds/1000, 0)
    minutes, seconds = divmod(delta.seconds, 60)
    hours, minutes   = divmod(minutes, 60)
    return hours, minutes, seconds, millis    

def get_timedelta_min_and_sec(delta):
    hours, minutes, seconds, millis = get_timedelta_values(delta)
    return str(f'{str(minutes).zfill(2)}:{str(seconds).zfill(2)}')

The 2nd function, get the delta values and creates a standard output with “mm:ss” format. So, not tricky and easy to move forward.

Another cool feature of the timedelta is that support adding. So as a final example, I’ll generate some random deltas in a loop, and add them in a totalTime var.

import time
import datetime
from random import randint

def get_timedelta_values(delta):
    # Get the hours, minutes, seconds and milliseconds
    millis           = round(delta.microseconds/1000, 0)
    minutes, seconds = divmod(delta.seconds, 60)
    hours, minutes   = divmod(minutes, 60)
    return hours, minutes, seconds, millis    

def get_timedelta_min_and_sec(delta):
    hours, minutes, seconds, millis = get_timedelta_values(delta)
    return str(f'{str(minutes).zfill(2)}:{str(seconds).zfill(2)}')

totalTime = None
i = 0
while i < 25:
    i = i + 1
    rndSleep = randint(1, 10)
    print(f'current iteration: {i} - rnd sleep: {rndSleep}')

    start = datetime.datetime.utcnow()
    time.sleep(rndSleep)
    end = datetime.datetime.utcnow()

    delta = end - start

    if (totalTime is None):
        totalTime = delta
    else:
        totalTime += delta

    print(f'  >> delta     : {get_timedelta_min_and_sec(delta)}')
    print(f'  >> total time: {get_timedelta_min_and_sec(totalTime)}')

The output as expected shows the delta with specific format in each iteration and also the accumulator for the total time

python adding time delta vars

So, here it is, a simple example that will save me some time in the future for sure !

Happy coding!

Greetings

El Bruno

ÂżCon ganas de ponerte al dĂ­a?

En Lemoncode te ofrecemos formaciĂłn online impartida por profesionales que se baten el cobre en consultorĂ­a:

References

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.