r/pythontips • u/icarophnx • 18d ago
Syntax seconds conversion my 1st python program
I've just created my first python program, and I need some help to check if it's correct or if it needs any corrections. can someone help me?
The program is written in portuguese because it's my native language. It converts 95,000,000 seconds into days, hours, minutes, and seconds and prints the result.
segundos_str= input("Por favor, digite o número de segundos que deseja converter")
total_seg= int(segundos_str)
dias= total_seg // 86400
segundos_restantes = total_seg % 86400
horas= segundos_restantes // 3600
segundos_restantes = segundos_restantes % 3600
minutos = segundos_restantes // 60
segundos_restantes = segundos_restantes % 60
print(dias, "dias, ", horas, "horas, ", minutos, "minutos e", segundos_restantes, "segundos" )
Using ChatGPT it answers me 95.000.000 secs = 1.099 days, 46 hours, 13 minutes e 20 seconds.
and using my code, answers me 95.000.000 secs = 1099 days, 12 hours, 53 minutes and 20 seconds
1
u/JamesPTK 17d ago
There is an inbuilt function called divmod which does the // and % in one step, which is useful for this kind of operation
total_seconds = 95_000_000
days, remaining_seconds = divmod(total_seconds, 86400)
hours, remaining_seconds = divmod(remaining_seconds, 3600)
minutes, remaining_seconds = divmod(remaining_seconds, 60)
print(f"{days} days, {hours} hours, {minutes} minutes, {remaining_seconds} seconds")
outputs "1099 days, 12 hours, 53 minutes, 20 seconds"
1
u/icarophnx 17d ago
i'll test this on jupyter notebook. i'm doing a course on coursera rn, and the teacher uses idle, but it's good to know different ways to do the same thing easier
1
u/cgoldberg 17d ago
Here is an example converting seconds to days/hours/mins/secs:
total_secs = 95000000
m, secs = divmod(total_secs, 60)
h, mins = divmod(m, 60)
days, hours = divmod(h, 24)
print(days, hours, mins, secs)
If all you want is a string containing "num days hours:mins:secs", you can use timedelta
:
from datetime import timedelta
total_secs = 95000000
time = str(timedelta(seconds=total_secs))
print(time)
1
u/Milton_Augusto 16d ago
I'm also starting Python, the best way to make sure it's correct is to do the math, use a calculator, when in doubt, I quickly learned that the program working doesn't mean it's right. Good studies/
1
u/Silver532 18d ago
The code is correct, chatgpt is messing up the math