Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a function that returns seconds into days, hours, mins and sec. But I need to However, not print if outputs are 0. For example, if I enter 176400 seconds I want output would be "2 day 1 hours" not "2 day, 2 hours, 0 minutes, 0 seconds".
I did so far:
sec = int(input("Enter time in Seconds: "))
temp = sec
day = sec // 86400
sec %= 86400
hour = sec // 3600
sec %= 3600
mins = sec // 60
sec %= 60
if day >= 1:
print(f'time in minutes is {day}days {hour}hour {mins}min {sec}sec')
elif hour >= 1:
if mins == 0 and sec == 0:
print(f'time in minutes is {hour}hour')
elif mins == 0:
print(f'time in minutes is {hour}hour {sec}sec')
elif sec == 0:
print(f'time in minutes is {hour}hour {mins}min')
else:
print(f'time in minutes is {hour}hour {mins}min {sec}sec')
elif mins >= 1:
if sec == 0:
print(f'time in minutes is {mins}min')
else:
print(f'time in minutes is {mins}min {sec}sec')
elif sec >= 1:
print(f'time sec == {sec} sec')
I could be continue This code using bunch of "if" statement, but is there shorter way to do this?
It looks like you're trying to do something like:
result = "time in minutes is"
if days >0:
result += f" {days} days"
if hours > 0:
result += f" {hours} hours"
if mins > 0:
result += f" {mins} minutes"
if secs > 0:
result += f" {secs} seconds"
IIUC, you want shorter way then you can use datetime.timedelta like below:
import datetime
sec = int(input('Enter the number of seconds: '))
print(datetime.timedelta(seconds=sec))
Output:
Enter the number of seconds: 86600
1 day, 0:03:20
You can add these lines to get what you want:
import datetime
sec = int(input('Enter the number of seconds: '))
str_tm = str(datetime.timedelta(seconds=sec))
day = str_tm.split(',')[0]
hour, minute, second = str_tm.split(',')[1].split(':')
print(f'{day}{hour} hour {minute} min {second} sec')
Output:
Enter the number of seconds: 176400
2 days 1 hour 00 min 00 sec
You can assemble the non-zero parts in a list and join it at the end. You can also use the divmod function to extract the days,hours,minutes and seconds:
sec = int(input("Enter time in Seconds: "))
time = []
days,sec = divmod(sec,86400) # sec will get seconds in partial day
if days:
time.append(f"{days} day"+"s"*(days>1))
hours,sec = divmod(sec,3600) # sec will get seconds in partial hour
if hours:
time.append(f"{hours} hour"+"s"*(hours>1))
minutes,sec = divmod(sec,60) # sec will get seconds in partial minute
if minutes:
time.append(f"{minutes} minute"+"s"*(minutes>1))
if sec:
time.append(f"{sec} second"+"s"*(sec>1))
Sample runs:
Enter time in Seconds: 176400
time is: 2 days, 1 hour
Enter time in Seconds: 1767671
time is: 20 days, 11 hours, 1 minute, 11 seconds
Enter time in Seconds: 259321
time is: 3 days, 2 minutes, 1 second
The whole thing could be simplified using a loop that goes through the divisors and time units:
sec = int(input("Enter time in Seconds: "))
time = []
for d,u in [(86400,"day"),(3600,"hour"),(60,"minute"),(1,"second")]:
n,sec = divmod(sec,d)
if n: time.append(f"{n} {u}"+"s"*(n>1))
print("time is:",", ".join(time))
Personally, I prefer using values that are more familiar (like 60 minutes in an hour) which would change the sequence a bit. Also, the time string could be assembled directly rather than use a list and join at the end:
sec = int(input("Enter time in Seconds: "))
time = ""
for d,u in [(60,"second"),(60,"minute"),(24,"hour"),(sec,"day")]:
sec,n = divmod(sec,d)
if n: time = f"{n} {u}" + "s"*(n>1) + ", "*bool(time) + time
print("time is:",time)
Related
def secondCalculator(days, hours, minutes, seconds):
days = int(input("Days: ")) * 3600 * 24
hours = int(input("Hours: ")) * 3600
minutes = int(input("Minutes: ")) * 60
seconds = int(input("Seconds: "))
allSec = days + hours + minutes + seconds
if days == 1:
print(f"{days} Days,{hours} Hours, {minutes} Minutes, {seconds} Seconds are equal to {allSec} seconds.")
#### same use of if, for hours, minutes and seconds.
If user enters
secondCalculator(0,1,2,5)
Output should be:
0 Day, 1 Hour, 2 Minutes, 5 Seconds is equal to 3725 seconds.
When user enters 1 day, it should be printing "day" not "days", same goes for hour, minutes, second.
The things is making it with an if is doable yes but i thought maybe there are easier ways to do it.
How can i make it put the "s" suffix depending on the entered number by the user.
Can we implement conditional string formatting for it?
Something like this possibly? Might make sense to wrap it in a function:
>>> days = 1
>>> f"day{('s', '')[days==1]}"
'day'
>>> days = 2
>>> f"day{('s', '')[days==1]}"
'days'
>>>
Use:
if days > 1:
suffix_day = 'days'
elif days == 0:
suffix_day = 'days'
else:
suffix_day = 'day'
then use:
print(f'{days} {suffix_day})
Define:
def s(val):
if val > 1:
return "s"
return ""
And use it as:
print(f"{days} Day{s(days)}
I have a for loop and I want each iteration to be executed every 5 minutes. Essentially, I want to freeze/sleep the loop for 5 minutes and then continue from where it left 5 minutes ago, NOT to start from the beginning. In total, I want to do this for an entire day (24hours).
Something like this? The loop runs for (a little more than) twenty-four hours and sleeps for five minutes after each iteration.
from time import sleep, time
ONE_DAY = 24 * 60 * 60 # seconds
FIVE_MINUTES = 5 * 60 # seconds
start_time = time()
current_time = start_time
while current_time <= start_time + ONE_DAY - FIVE MINUTES:
# Do something loopy here...
time.sleep(FIVE_MINUTES)
current_time = time()
You could define a method that simply calls sleep for 5 minutes and then call that in your loop. Kind of like this
import time
# main loop
for i in .....:
# do your stuff
wait5Mins()
# continue doing stuff
def wait5Mins():
time.sleep(300)
I'm programming some code that allows a user to input seconds, and receive how many days, hours, minutes, and seconds it churns out to. However, if I enter any number larger than 311039999, the amount of hours goes to 24+, instead of 0.
Right now I have something programmed in that tells the user that the number is too large if it exceeds the aforementioned value, but I want to change it so that it's not a problem anymore.
Here is my code:
user_sec= int(input("How many seconds are there? "))
#When max value is minutes, displays number of minutes
tot_min_min = user_sec/60
#When max value is minutes, displays number of seconds
tot_min_sec = user_sec%60
#When max value is hours, displays number of hours
tot_hr_hr = user_sec/3600
#When max value is hours, displays number of minutes
tot_hr_min = tot_min_min%60
#When max value is hours, displays number of seconds
tot_hr_sec = user_sec%60
#When max value is days, displays number of days
tot_day_day = user_sec/86400
#When max value is days, displays number of hours
tot_day_hr = tot_hr_hr/3600
#When max value is days, displays number of minutes
tot_day_min = tot_hr_min%60
#When max value is days, displays number of seconds
tot_day_sec = user_sec%60
if user_sec >= 311040000:
print 'Your number is too large to calculate.'
elif user_sec >= 60 and user_sec < 3600:
print '{} seconds makes {} minute(s) and {} second(s).'.format(user_sec,tot_min_min,tot_min_sec)
elif user_sec >= 3600 and user_sec < 86400:
print '{} seconds makes {} hour(s), {} minute(s) and {} second(s).'.format(user_sec,tot_hr_hr,tot_hr_min,tot_hr_sec)
elif user_sec >= 86400 and user_sec < 311040000:
print '{} seconds makes {} days(s), {} hour(s), {} minute(s) and {} second(s).'.format(user_sec,tot_day_day,tot_day_hr,tot_day_min,tot_day_sec)
else:
print 'There is/are {} second(s).'.format(user_sec)
I'm using Canopy, if this helps. Simple answers are appreciated, since I've only been doing this for a few weeks.
[EDIT] Here's an example of my problem. If user_sec = 1000000000, it prints out '1000000000 seconds makes 11574 days(s), 77 hour(s), 46 minute(s) and 40 second(s).' I'm not sure where the mathematical issue is, but the correct answer is '11574 days, 1 hour, 46 minutes and 40 seconds.'
If you don't mind using a 3rd party module, dateutil provides an easy way to do this:
from dateutil.relativedelta import relativedelta
user_sec = int(input("How many seconds are there? "))
d = relativedelta(seconds=user_sec)
print(d)
This will output the following if you enter 351080000
relativedelta(days=+4063, hours=+10, minutes=+13, seconds=+20)
From there you can print out a more user friendly string:
print('{0} seconds makes {1.days} days(s), {1.hours} hour(s), {1.minutes} minute(s) and {1.seconds} second(s).'.format(user_sec, d))
351080000 seconds makes 4063 days(s), 10 hour(s), 13 minute(s) and 20 second(s).
Otherwise it is pretty straightforward to calculate the days. hours, minutes and seconds:
n = user_sec
days, n = divmod(n, 86400)
hours, n = divmod(n, 3600)
minutes, n = divmod(n, 60)
seconds = n
print('{} seconds makes {} days(s), {} hour(s), {} minute(s) and {} second(s).'.format(user_sec, days, hours, minutes, seconds))
I want to convert a time.time() object to minutes.
In my program, I did this:
import time
start = time.time()
process starts
end = time.time()
print end - start
Now I have the value 22997.9909999. How do I convert this into minutes?
You've calculated the number of seconds that have elapsed between start and end. This is a floating-point value:
seconds = end - start
You can print the number of minutes as a floating-point value:
print seconds / 60
Or the whole number of minutes, discarding the fractional part:
print int(seconds / 60)
Or the whole number of minutes and the whole number of seconds:
print '%d:%2d' % (int(seconds / 60), seconds % 60)
Or the whole number of minutes and the fractional number of seconds:
minutes = int(seconds / 60)
print '%d m %f s' % (minutes, seconds - 60 * minutes)
I'm trying to code a Python script for 'Enter the number of Seconds' and get results in weeks, days, hours, minutes and seconds. Here is what I have, but I am not getting the correct answers. What am I doing wrong?
seconds = raw_input("Enter the number of seconds:")
seconds = int(seconds)
minutes = seconds/60
seconds = seconds % 60
hours = minutes/60
hours = seconds/3600
minutes = minutes % 60
days = hours/24
days = minutes/1440
days = seconds/86400
hours = hours % 60
hours = minutes % 60
hours = seconds % 3600
weeks = days/7
weeks = hours/168
weeks = minutes/10080
weeks = seconds/604800
days = days % 1
days = hours % 24
days = minutes % 1440
days = seconds % 86400
weeks = weeks % 1
weeks = days % 7
weeks = hours % 168
weeks = minutes % 10080
weeks = seconds % 604800
print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', seconds, 'seconds'
Just from the basic conversion principles:
weeks = seconds / (7*24*60*60)
days = seconds / (24*60*60) - 7*weeks
hours = seconds / (60*60) - 7*24*weeks - 24*days
minutes = seconds / 60 - 7*24*60*weeks - 24*60*days - 60*hours
seconds = seconds - 7*24*60*60*weeks - 24*60*60*days - 60*60*hours - 60*minutes
A bit of a less noisy way of doing the same thing:
weeks = seconds / (7*24*60*60)
seconds -= weeks*7*24*60*60
days = seconds / (24*60*60)
seconds -= days*24*60*60
hours = seconds / (60*60)
seconds -= hours*60*60
minutes = seconds / 60
seconds -= minutes *60
A cleaner version of again the same thing with divmod function which returns both division result and remainder in a tuple (division, remainder):
weeks, seconds = divmod(seconds, 7*24*60*60)
days, seconds = divmod(seconds, 24*60*60)
hours, seconds = divmod(seconds, 60*60)
minutes, seconds = divmod(seconds, 60)
Basically, this solution is closest to your attempt since this is what divmod does:
weeks, seconds = divmod(seconds, 7*24*60*60)
equivalent to
weeks = seconds / (7*24*60*60)
seconds = seconds % (7*24*60*60)
Here we are essentially finding the number of whole weeks in our time and keeping what is left after these weeks are removed.
And also you can go from the other end to make it even prettier:
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
The idea behind this is that the number of seconds in your answer is the remainder after dividing them in minutes; minutes are the remainder of dividing all minutes into hours etc... This version is better because you can easily adjust it to months, years, etc...
Using Python's datetime timedeltas with support for milliseconds or microseconds.
import datetime
def convert(sec):
td = datetime.timedelta(seconds=sec, microseconds=sec-int(sec))
return td.days/7, (td.days/7)%7, td.seconds/3600, (td.seconds/60)%60, td.seconds%60, td.microseconds, td.microseconds/1000
seconds = 8*24*60*60 + 21627.123 # 8 days, 6 hours (21600 seconds), 27.123 seconds
w, d, h, m, s, us, ms = convert(seconds)
print '{}s / {}w {}d {}h {}m {}s {}us {}ms'.format(seconds,w,d,h,m,s,us,ms)
712827.123s / 1w 1d 6h 0m 27s 123000us 123ms
def humanize_duration(amount, units='s'):
INTERVALS = [(lambda mlsec:divmod(mlsec, 1000), 'ms'),
(lambda seconds:divmod(seconds, 60), 's'),
(lambda minutes:divmod(minutes, 60), 'm'),
(lambda hours:divmod(hours, 24), 'h'),
(lambda days:divmod(days, 7), 'D'),
(lambda weeks:divmod(weeks, 4), 'W'),
(lambda years:divmod(years, 12), 'M'),
(lambda decades:divmod(decades, 10), 'Y')]
for index_start, (interval, unit) in enumerate(INTERVALS):
if unit == units:
break
amount_abrev = []
last_index = 0
amount_temp = amount
for index, (formula, abrev) in enumerate(INTERVALS[index_start: len(INTERVALS)]):
divmod_result = formula(amount_temp)
amount_temp = divmod_result[0]
amount_abrev.append((divmod_result[1], abrev))
if divmod_result[1] > 0:
last_index = index
amount_abrev_partial = amount_abrev[0: last_index + 1]
amount_abrev_partial.reverse()
final_string = ''
for amount, abrev in amount_abrev_partial:
final_string += str(amount) + abrev + ' '
return final_string