Search code examples
pythondatetimeiotdatetime-formatstrftime

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


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'

Solution

  • 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