Python Forum

Full Version: Converting a remainder to int to str
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm converting seconds to HH:MM:SS and having a hard time converting a remainder (seconds) to an integer to a string Confused .
I found this code online and it looks good but I cannot join it as a string HH:MM:SS because I cannot convert a remainder (seconds) ->int ->string.
Here is the code:
sec = 50007
sec_value = int(sec % (24 * 3600))
hour_value = str(int(sec_value // 3600))
sec_value %= (int(3600))
min = str(int(sec_value // 60))
sec_value %= 60

print("Converted hours:  ",hour_value)
print("Converted minutes:",min)
print("Converted seconds:",sec_value)
print ("Cannot add Seconds. Only hours and minutes :   "+hour_value+":"+min+":"+"Seconds here")
Thank you!
Is there a reason you can't use str() like you do for your hours and minutes? You could assign it to a new variable or just use it directly in your print statement.
print(hour_value+":"+min+":"+str(sec_value))
Also, it would be best to avoid using min as a variable name since it is the name of a built-in function in Python.
I think that one should start from another end by dividing seconds with 60 (to get seconds which don't fit into minutes), then dividing floor with 60 (to get minutes which don't fit into hours) and then divide with 60 to get hours. There is built-in divmod() for this type of calculations:

EDIT: following is code which doesn't deliver expected results but kept for context. Refer to second code snippet

>>> seconds = 50007
>>> timeunits = list()
>>> for i in range(3):                      # for sec, min and hrs
...    seconds, unit = divmod(seconds, 60)  
...    timeunits.insert(0, unit)
...
>>> timeunits
[13, 53, 27]
>>> ':'.join(str(unit) for unit in timeunits)
'13:53:27'
Second snippet delivering expected results:

>>> seconds = 500007
>>> minutes, seconds = divmod(seconds, 60)
>>> hours, minutes = divmod(minutes, 60)
>>> print(f'{hours}:{minutes}:{seconds}')
138:53:27
If this is just for time, consider using datetime for the conversion directly:

>>> import datetime
>>> print(datetime.timedelta(seconds=50007))
13:53:27
what I actually need is to have all the "hours" added without converting it to days.

if I ran this script the outcome is "18:53:27" but it should be "138:53:27"

sec = 500007
sec_value = int(sec % (24 * 3600))
hour_value = str(int(sec_value // 3600))
sec_value %= (int(3600))
min = str(int(sec_value // 60))
sec_value %= 60
print(hour_value+":"+min+":"+str(sec_value))
Thank you!
Yeah, datetime won't do that for you easily. If you need hours > 24, then you'll have to do the division yourself as elsewhere in the thread.
I thought there is an easy way, I guess Python not really that flexible Dodgy .

Thank you, guys!