0

below a simple example using the Python interpreter:

>>> import datetime
>>> 
>>> time=datetime.timedelta(seconds=10)
>>> str(time)
'0:00:10'
>>>

how can I change the syntaxt of the time object when I convert it in a string? As reslt, I want to see '00:00:10' and not '0:00:10'. I really don't understand why the last zero in the hours block is missing, I want to see always two digits in each block. how can I do it?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
TurboC
  • 777
  • 1
  • 5
  • 19
  • 2
    Why are you using a `timedelta` instead of an actual `datetime.time` or `datetime.datetime`? The latter can be formatted with `datetime.strftime` (or with normal format strings or f-strings) that gives you full control, just read the `datetime` docs. – ShadowRanger Nov 25 '22 at 02:13
  • so how con I convert seconds to hours, minutes and seconds without using "timedelta"? what is the right syntaxt? then I need to take the string in this format '%H:%M:%S'. – TurboC Nov 25 '22 at 02:42
  • @ShadowRanger: `datetime.timedelta` is the right type to express "10 seconds". `datetime.time` would be the right type to express something like "12:00:10 AM", but it doesn't sound like that's the goal here. – user2357112 Nov 25 '22 at 03:29

1 Answers1

2

You have to create your custom formatter to do this.

Python3 variant of @gumption solution which is written in python2. This is the link to his solution

Custom Formatter

from string import Template

class TimeDeltaTemp(Template):
    delimiter = "%"

def strfdtime(dtime, formats):
    day = {"D": dtime.days}
    hours, rem = divmod(dtime.seconds, 3600)
    minutes, seconds = divmod(rem, 60)
    day["H"] = '{:02d}'.format(hours)
    day["M"] = '{:02d}'.format(minutes)
    day["S"] = '{:02d}'.format(seconds)
    time = TimeDeltaTemp(formats.upper())
    return time.substitute(**day)

Usage


import datetime

time=datetime.timedelta(seconds=10)
print(strfdtime(time, '%H:%M:%S'))
time=datetime.timedelta(seconds=30)
print(strfdtime(time, '%h:%m:%s'))

Output

00:00:10
00:00:30
Maxwell D. Dorliea
  • 1,086
  • 1
  • 8
  • 20
  • cool, but is it the only way to reach my goal? I mean, must I really create a custom class and function? – TurboC Nov 25 '22 at 02:49
  • I'm sure there's another way but I think this will be more cleaner. – Maxwell D. Dorliea Nov 25 '22 at 02:58
  • Your solution fixes another point. **time=datetime.timedelta(seconds=10000000)** for example, covenrted in a string, is **115 days, 17:46:40** but your code get always the '%h:%m:%s' output with the hour block fixed, and it was exactly what I wanted to see. good job! – TurboC Nov 25 '22 at 11:11