How to get hour format in two digit (00.00.00) in python?

Viewed 2671

Below is the sample code I am using inside my one of the application. I want Default hour format as 00 (e.g. 02:30:35) and here I am getting as 0:00:03.011445 so I am using strftime but I am getting another exception there. Please guide on it.

from datetime import datetime
from datetime import time
from time import strftime
import time

start = datetime.now()
time.sleep(3)
end = datetime.now()

print(start)
print(end)
dt = (end - start)
print('Defual Time:', dt)

print('New Format DateTime', dt.strftime("%m/%d/%y %H:%M:%S"))

I am getting below output.

2020-10-17 19:15:36.831928
2020-10-17 19:15:39.843373
Defualt Time: 0:00:03.011445
Traceback (most recent call last):
  File "D:/New folder/IoT2.py", line 30, in <module>
    print('New Format DateTime', dt.strftime("%m/%d/%y %H:%M:%S"))
AttributeError: 'datetime.timedelta' object has no attribute 'strftime'
3 Answers

u can just get seconds and days from a datetime.timedelta so u can do something like this!

from datetime import datetime
import time

start = datetime.now()
time.sleep(3)
end = datetime.now()

print(start)
print(end)
dt = (end - start)
print('Default Time:', dt)

def days_hours_minutes(td):
    x = (td.days, td.seconds//3600, (td.seconds//60)%60, td.seconds)
    return x #(days, hrs, mins, seconds)

print('New Format DateTime', days_hours_minutes(dt))

You can use the method total_seconds of the timedelta object and calculate the respective hours minutes and second by yourself and then you can format the output string as you want.

from datetime import datetime
from datetime import time
from time import strftime
import time

start = datetime.now()
time.sleep(3)
end = datetime.now()

print(start)
print(end)
dt = (end - start)
print('Defual Time:', dt)

dt_sec=dt.total_seconds()
hours,rem=divmod(dt_sec,3600)
minutes,rem=divmod(rem,60)

print('New Format DateTime', f'{hours:0>2.0f}:{minutes:0>2.0f}:{rem:0>2.0f}:'+f'{rem:.3f}'[-3:])

Edit

I added also the printing of the milliseconds.

The reason why you are getting the Attribute Error is because strftime belongs to datetime.datetime class ( from datetime.now()) and not datetime.timedelta class (from end-start).

Instead, you can actually use total_seconds() method to fetch the seconds of the time difference and format it in string however you wish.

Edit: You can use microseconds attribute of timedelta to calculate your milliseconds and format it to display.

from datetime import datetime
from datetime import time
from time import strftime
import time

start = datetime.now()
time.sleep(3)
end = datetime.now()

print(start)
print(end)
dt = (end - start)
print('Default Time:', dt)

milliseconds = int(round(dt.microseconds/1000, 1))

dt = int(dt.total_seconds())

print('New format: {:02}:{:02}:{:02}:{:03}'.format(dt // 3600, dt % 3600 // 60, dt % 60, milliseconds))

The output for this would be:

2020-10-19 13:02:13.861103
2020-10-19 13:02:16.863268
Default Time: 0:00:03.002165
New format: 00:00:03:002
Related