3

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'
Heikki
  • 2,214
  • 19
  • 34
Amaze_Rock
  • 163
  • 3
  • 16
  • Does this answer your question? [Format timedelta to string](https://stackoverflow.com/questions/538666/format-timedelta-to-string) – FObersteiner Oct 17 '20 at 14:05

3 Answers3

0

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))
Shashwat Agrawal
  • 105
  • 1
  • 10
0

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.

flabons
  • 331
  • 1
  • 8
0

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
  • Thanks. Thats cool... but one query is how to continue with milisconds? because I need entire milliseconds too... – Amaze_Rock Oct 19 '20 at 04:57
  • For milliseconds, use `print(round(dt.microseconds/1000,2))` before converting dt type to int. – Sudharsan Balajee Oct 19 '20 at 11:46
  • Hi, no its returning wrong value. like this. Milliseconds are not coming with new format. 2020-10-19 17:36:30.792681 2020-10-19 17:36:33.793254 Default Time: 0:00:03.000573 0.57 New format: 00:00:03 – Amaze_Rock Oct 19 '20 at 12:07
  • Hey, I have edited the code to include the millisecond format as required. Let me know if it solves your issue – Sudharsan Balajee Oct 19 '20 at 13:05
  • Output of your code is 2020-10-19 19:19:42.015249 2020-10-19 19:19:45.016215 Default Time: 0:00:03.000966 New format: 00:00:03:001. What we need that, the value in new format should 00:00:03.000966. One more thing. – Amaze_Rock Oct 19 '20 at 13:51
  • Try this : `milliseconds = dt.microseconds dt = int(dt.total_seconds()) print('New format: {:02}:{:02}:{:02}:{:06}'.format(dt // 3600, dt % 3600 // 60, dt % 60, milliseconds))` – Sudharsan Balajee Oct 19 '20 at 14:42
  • Awesome! Glad to help :) – Sudharsan Balajee Oct 19 '20 at 16:15