0

So far I did something like this:

import datetime as dt
import time, sys
start = time.time() 

while True:
    now = time.time()
    delta = dt.timedelta(seconds=int(now - start))
    sys.stdout.write('\r\033[2K' + str(delta))
    time.sleep(.1)

But it prints it as a simple H:M:S method 0:11:11 and I need to do something like 3d, 21h, 46m, 12s that automatically filters out some output if the value is still 0. How can I do that?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Ruri
  • 139
  • 12

2 Answers2

2

You can use datetime.now instead of time.time and then convert it to timedelta .

start = dt.datetime.now()
now = dt.datetime.now()
print(frmtdelta(now - start))

You need to write a function to compute hour, minute and second. (We have days in timedelta.)

import datetime as dt
import time

def frmtdelta(delta):
    d = {"days": delta.days}
    d["hr"], rem = divmod(delta.seconds, 3600)
    d["min"], d["sec"] = divmod(rem, 60)
    return "{days}d, {hr}h, {min}m, {sec}s".format(**d)


start = time.time() 
while True:
    now = time.time()
    delta = dt.timedelta(seconds=int(now - start))
    print(frmtdelta(delta))
    time.sleep(.1)

Output:

0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 0s
0d, 0h, 0m, 1s
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • This answer does not filter out a value if the value is 0. – Albin Sidås Jul 18 '22 at 05:22
  • That was kind of you! I just was wondering regarding the questionline " that automatically filters out some output if the value is still 0. How can I do that?" But yes, it will fully and correctly display all the timevalues :) – Albin Sidås Jul 18 '22 at 06:06
1

You could try building a string where if there is no value for a time you just do not append it to the string:

def build_time_string(delta):
    # Define all the available time data
    times = [
        ["d", delta.days],
        ["h", delta.hour],
        ["m", delta.minute],
        ["s", delta.second]
    ]

    # Build the list of values which are not 0
    time_string = []
    for time in times:
        if time[1] != 0:
            time_string.append(str(time[1] + time[0])

    # Join the string and add the comma seperator
    return ", ".join(time_string)
        

With this function you can edit your solution to:

import datetime as dt
import time, sys
start = time.time() 

while True:
    now = time.time()
    delta = dt.timedelta(seconds=int(now - start))
    sys.stdout.write(build_time_string(delta)
    time.sleep(.1)
Albin Sidås
  • 321
  • 2
  • 10