-4

I would like to change the format of timedelta print

    end_time = time()
    r_time = (end_time - start_time)
    m = "{}".format(str(timedelta(seconds=r_time)))

Currently I'm getting 00:00:00 and will like to change for 00.00 , just minutes and seconds

mar24n
  • 123
  • 2
  • 10
  • 3
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). Stack Overflow is not intended to replace existing documentation and tutorials. `timedelta` formats are documented quite well; we expect you to incorporate that knowledge into your question. – Prune Feb 19 '21 at 23:11
  • Do you want/need to convert the hours component into minutes, or just drop it? – mhawke Feb 19 '21 at 23:26
  • @mhawke just drop it just need minutes and second and `.` as separator – mar24n Feb 19 '21 at 23:31
  • There's lots of info on this here: https://stackoverflow.com/questions/538666/format-timedelta-to-string – GAP2002 Feb 20 '21 at 00:28
  • 1
    @mar24n: you should add your `divmod()` solution as an answer. – mhawke Feb 20 '21 at 00:46
  • @mhavke ok, thanks – mar24n Feb 20 '21 at 00:47

2 Answers2

1

You can't do much in terms of formatted string conversions with a timedelta. You could just convert to a string and grab the last 5 characters:

>>> r_time = 1000
>>> str(timedelta(seconds=r_time))[-5:]
'16:40'

Other, less hacky ways exist such as the following which does not require mucking about with timedelta:

>>> time.strftime('%M:%S', time.gmtime(r_time))
'16:40'
>>> time.strftime('%M:%S', time.gmtime(3599))
'59:59'
>>> time.strftime('%M:%S', time.gmtime(3600))
'00:00'

I was tempted by this:

>>> r_time = 1000
>>> f'{r_time//60:02}:{r_time%60:02}'
'16:40'

but then this happens:

>>> r_time = 3600
>>> f'{r_time//60:02}:{r_time%60:02}'
'60:00'
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • `>>> f'{r_time//60}:{r_time%60}' '16:40'` that's looks good , but unfortunately in my case i can't use `fstring` with `Micropython` – mar24n Feb 20 '21 at 00:58
0

Found another solution

r_time = (end_time - start_time)

seconds = abs(int(r_time))

minutes, seconds = divmod(seconds, 60)
times = '%i.%i' % (minutes, seconds)

That's gave me exactly the format what i was looking for 00.00

mar24n
  • 123
  • 2
  • 10