Evaluating time with python [duplicate] - python

This question already has answers here:
How do I convert seconds to hours, minutes and seconds?
(18 answers)
Closed 10 months ago.
I need to write a program that reads in seconds as input, and outputs the time in hours, minutes, and seconds using python.
seconds = int(input())
minutes = seconds // 60
hours = minutes // 3600
seconds_left = + (seconds - hours)
print(f'Hours: {hours}')
print(f'Minutes: {minutes}')
print(f'Seconds: {seconds_left}')
This is what I'm currently running and it's not getting the desired output. Question in mind uses 4000 as an input and outputs 1 hour, 6 min, and 40 seconds

When you divide to get (e.g.) the hours, you should also take the mod in order to just carry forward the remainder:
>>> seconds = 4000
>>> hours = seconds // 3600
>>> seconds = seconds % 3600
>>> minutes = seconds // 60
>>> seconds = seconds % 60
>>> hours, minutes, seconds
(1, 6, 40)
This is equivalent to multiplying the int quotient by the divisor and subtracting:
>>> seconds = 4000
>>> hours = seconds // 3600
>>> seconds -= hours * 3600
>>> minutes = seconds // 60
>>> seconds -= minutes * 60
>>> hours, minutes, seconds
(1, 6, 40)

Related

Converting seconds into days, hours, minutes & seconds in Python [closed]

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)

Python Military Time formula and string formatting

I have created a function to take a string input "minutes-since-midnight" and convert it into military time.For example- 365 = 0605,441 = 0721,864 = 1424. For some reason my outputs are: 066, 077, 1414. Can someone please explain to me what I am doing wrong
def military_time(minutes):
if minutes < 600:
hour = minutes // 60
minute = minutes % 60
print("0{0:0}{0:0}".format(hour,minute))
elif 600 < minutes < 720:
hour = minutes // 60
minute = minutes % 60
print("{0:0}{0:0}".format(hour,minute))
elif minutes == 720:
hour = 1200
print(hour)
else:
hour = ((minutes-720) // 60) + 12
minute = (minutes) % 60
print("{0:0}{0:0}".format(hour,minute))
you can use format to pad your integers with zeros if necessary:
def military_time(minutes):
minutes %= 1440 # does not make sense if more than 24h
h, m = divmod(minutes, 60)
print("{0:02d}{1:02d}".format(h, m))
military_time(365) # 0605
military_time(441) # 0721
military_time(864) # 1424
also note that your format string referenced the first argument twice (you had {0}{0} instead of {0}{1}).

Convert time object to minutes in Python 2

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)

How can you split a decimal number at the decimal to get minutes and seconds? Python [duplicate]

This question already has answers here:
Convert DD (decimal degrees) to DMS (degrees minutes seconds) in Python?
(12 answers)
Closed 7 years ago.
Say I have a variable called
time = 6.50
how can I split the number so that I can output to the user:
print("Your total time was %i minutes and %i seconds. " %(minute, second))
I thought about converting them to string but I need to be able to multiply the .50 part by 60 so I can get the total seconds.
You can also use divmod , as -
minutes, seconds = divmod(int(time * 60), 60)
If you want the seconds to also have millisecond (floating point precision) , you can remove the conversion to int and do - divmod(time * 60, 60) .
Demo -
>>> time = 6.50
>>> divmod(time * 60, 60)
(6.0, 30.0)
>>> time = 6.55
>>> divmod(time * 60, 60)
(6.0, 33.0)
>>> time = 6.53
>>> divmod(time * 60, 60)
(6.0, 31.80000000000001)
>>> time = 6.55
>>> divmod(int(time * 60), 60)
(6, 33)
But please note, floating point arithematic is not precise, so you may get approximate values instead of exact accurate results.
time = 6.50
minute, second = int(time), (time%1)*60
print("Your total time was %i minutes and %i seconds. " %(minute, second))

Convert seconds to weeks-days-hours-minutes-seconds in Python

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

Categories

Resources