Taking a coursera course and stuck and defining functions. I'm not really sure what I'm doing wrong.
Here is the question being posed:
Flesh out the body of the print_seconds function so that it prints the total amount of seconds given the hours, minutes, and seconds function parameters. Remember that there are 3600 seconds in an hour and 60 seconds in a minute.
Here is my sample code:
def print_seconds(hours, minutes, seconds):
print("3600" + hours)
print ("60" + minutes)
print ("1" + seconds)
print_seconds(1,2,3)
These are what the current errors are:
Error on line 6:
print_seconds(1,2,3)
Error on line 2:
print("3600" + hours)
TypeError: must be str, not int
It's just:
def print_seconds(hours, minutes, seconds):
total = (3600 * hours) + (60 * minutes) + seconds
print(total)
The issue is that you have quoted "3600" this makes it a string type variable, and python is complaining that it doesn't know how to add a string to an integer (which is what is being passed when you call print_seconds(1,2,3). The other answer is trying to tell you to not quote the integer values and the type casting/addition will work out for you.
Or if you want you can just:
def print_seconds(hours, minutes, seconds):
print((3600*hours) + (60*minutes) + seconds)
If you're trying to get the total seconds, you have to multiple each parameter by an int, not a str. Also you're adding a string to the value, don't you want to multiply?
def print_seconds(hours, minutes, seconds):
print(hours * 3600)
print(minutes * 60)
print(seconds)
print_seconds(1,2,3)
def print_seconds(hours, minutes, seconds):
print (3600*hours + 60*minutes + seconds)
print_seconds(1,2,3)
def print_seconds(hours, minutes, seconds):
print((3600hours) + (60minutes) + (seconds)
Print_seconds(1,2,3)
Related
The task is to convert an input in seconds to a time that is readable for humans in the format HH:MM:SS.
import time
def make_readable(seconds):
return time.strftime('%H:%M:%S', time.gmtime(seconds))
So far this is what I have, and it works.
The only problem is that the hours should be displayed in a range from 00 - 99, currently it is in 24 hours.
e.g. with an input of 359999 seconds, it should output 99:59:59. This is also the maximum time by the way.
Errors:
'00:00:00' should equal '24:00:00'
'03:59:59' should equal '99:59:59'
'20:36:54' should equal '44:36:54'
Question: How to put the hours in the 99 format?
I think you can roll your own seconds parser. For example:
def make_readable(seconds):
if seconds > 359999:
raise ValueError('Invalid number of seconds: {}'.format(seconds))
s = seconds % 60
seconds //= 60
m = seconds % 60
seconds //= 60
h = seconds
return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
print(make_readable(359999)) # Prints 99:59:59
print(make_readable(65)) # Prints 00:01:05
Here is a solution using divmod instead of the time module.
def make_readable(seconds):
hours, rem = divmod(seconds, 3600)
minutes, seconds = divmod(rem, 60)
# The following makes sure a one-digit time quantity is written as 0X
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
Here are output examples.
make_readable(359999) # '99:59:59'
make_readable(3661) # '01:01:01'
# This will continue working over 35,999 seconds
make_readable(360000) # '100:00:00'
The time module provides a function, also named time ,that return the current Greenwich Mean Time in "the epoch",which is an arbitrary time used as a reference
point.On UNIX systems, the epoch is 1 January 1970.
> import time
> time.time()
1437746094.5735958
write a script that reads the current time and converts it to a time of a day in hours, minutes, and seconds ,plus the number of days since the epoch.
I don't see how this exercise connect to the chapter 5.Conditionals and Recursion and how to write code to make this happen?
Thinks for answering my question.
So, as your advice, i wrote a section of code like this:
import time
secs = time.time()
def time():
mins = secs / 60
hours = mins / 60
days = hours/24
print 'The minues:',mins,'The hours:' ,hours, 'The days:',days
print 'The seconds:', secs, time()
It output the result like this:
The seconds:1481077157.6 The minues:24684619.2933 The hours:411410.321554 The days:17142.0967314 none, My question is where is "none" come from?
import time
def current_time():
current=time.time()
t_sec = current % 86400
c_hours = int(t_sec/3600)
t_minutes = int(t_sec/60)
c_mins = t_minutes % 60
c_sec = int(t_sec % 60)
days=int(current/86400)
print("The Current time is",c_hours,':',c_mins,':',c_sec)
print('Days since epoch:', days)
>import time
>epoch=time.time()
>#60*60*24=86400
>total_sec = epoch % 86400
>#60*60
>hours = int(total_sec/3600)
>total_minutes = int(total_sec/60)
>mins = total_minutes % 60
>sec = int(total_sec % 60)
>days=int(epoch/86400)
>print("The Current time is",hours,':',mins,':',sec)
>print("Days since epoch:", days)
EDIT in response to: "My question is where is "none" come from?"
In your print function at the end, you call 'time()', but you do not return anything, thus it prints 'None'.
If you want 'None' gone, try this:
import time
secs = time.time()
def time():
mins = secs / 60
hours = mins / 60
days = hours/24
print ('The minues:',mins,'The hours:' ,hours, 'The days:',days)
time()
print ('The seconds:', secs)
Though the point should probably be, that if you want to use a recursive function, you should return something that you then use to calculate with.
Let's have a look at the exercise description:
Write a script that reads the current time and converts it to a time of a day in hours, minutes, and seconds, plus the number of days since the epoch.
How I understand the question, is that the answer should be formatted something like this:
Today is 18 hours, 12 minutes, 11 seconds and 18404 days since epoch.
To get this answer, you could use a function using 'modulus operator', which is a part of paragraph 5.1. You could then subtract the variable containing 'today' with the number of days, then the hours, minutes and seconds. This is somewhat a recursive process, which could help your understanding for subsequent exercises.
import time
#the epoch time
epoch = int(time.time())
#calculate number of days since epoch
days = epoch / (60 * 60 * 24)
hour = days % int(days) * 24
min = hour % int(hour) * 60
sec = min % int(min) * 60
print(f"Days since epoch: {int(days)}\nCurrent Time: {int(hour)}:{int(min)}:{int(sec)}")
I am using python, and would like to read a log file that contain info about time.
The string is like this: "1 hour and 22.5 seconds". or "41 seconds" or "22.3 seconds"; Not sure exactly what would be the best way to handle this case. I do not have control on how the data is written, I can just process it.
I was thinking to read the string; then separate it in single strings; so if I find "hour" at position [2] in the string list, I add 3600 seconds in an int variable; if I find minutes then I get the value and check if it has decimals or not, and parse it as such; adding it to the hours if present.
Is this something reasonable or there is a better way? Kinda prone to error to base your conversion on positions that may not be the same for different strings.
Using regular expressions:
UNIT2SECONDS = {
'hour': 3600,
'minute': 60,
'second': 1,
}
text = "4 hours, 43 minutes and 3 seconds"
seconds = sum(sum(map(float, re.findall("([.0-9]+)\s+%s" % k))) * v for k, v in UNIT2SECONDS.items())
Without regex, you can do something like this:
times = ['1 hour and 22.5 seconds', '3 hours 4 minutes and 15 seconds', '22.3 seconds', '6 hours']
# attempt to normalize the input data
times = [t.lower().replace('and','').replace('hours','hour').replace('minutes','minute').replace('seconds','second').replace(' ',' ') for t in times]
secondsList = map(getseconds, times)
def getseconds(sTime):
seconds = 0.0
S = sTime.split()
if 'hour' in S:
seconds += (3600 * float(S[S.index('hour')-1]))
if 'minute' in S:
seconds += (60 * float(S[S.index('minute')-1]))
if 'second' in S:
seconds += float(S[S.index('second')-1])
return seconds
I think your idea is not bad. I would use regex to find the occurences of hours, minutes and seconds and use grouping to get the corresponding number. As an example for the case of hours, consider this:
hours = re.match(r'(\d{1,2})(\shour[s]?)', "1 hour and 50 minutes")
if hours:
seconds = hours.group(1) * 60 * 60
The brackets () allow for grouping, which allow you to easily extract the number. You can perform the same for minutes and seconds. If the regex does not return anything, hours will be None, thus you can easily check for if hours: and then perform your math on the converted string.
this is my code:
last_time = get_last_time()
now = time.time() - last_time
minute =
seconds =
print 'Next time you add blood is '+minute+':'+seconds
Because recovery blood every 5 minutes so only need minute and second
thanks
This is basic time arithmetics...if you know that a minute has 60 seconds then you could
have found that yourself:
minute = int(now / 60)
seconds = int(now % 60)
I believe the difference between two time objects returns a timedelta object. This object has a .total_seconds() method. You'll need to factor these into minutes+seconds yourself:
minutes = total_secs % 60
seconds = total_secs - (minutes * 60)
When you don't know what to do with a value in Python, you can always try it in an interactive Python session. Use dir(obj) to see all of any object's attributes and methods, help(obj) to see its documentation.
Update: I just checked and time.time() doesn't return a time object, but a floating point representing seconds since Epoch. What I said still applies, but you get the value of total_secs in a different way:
total_secs = round(time.time() - last_time)
So in short:
last_time = get_last_time()
time_diff = round(time.time() - last_time)
minute = time_diff / 60
seconds = time_diff % 60 # Same as time_diff - (minutes * 60)
print 'Next time you add blood is '+minute+':'+seconds
In Python 3,
>>import time
>>time.localtime()
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=16, tm_hour=1, tm_min=51, tm_sec=39, tm_wday=0, tm_yday=197, tm_isdst=0)
You can scrape the minutes and seconds like that,
>>time.localtime().tm_min
51
>>time.localtime().tm_sec
39
I think, this can solve your problem.
I have a script here (not my own) which calculates the length of a movie in my satreceiver. It displays the length in minutes:seconds
I want to have that in hours:minutes
What changes do I have to make?
This is the peace of script concerned:
if len > 0:
len = "%d:%02d" % (len / 60, len % 60)
else:
len = ""
res = [ None ]
I already got the hours by dividing by 3600 instead of 60 but can't get the minutes...
Thanks in advance
Peter
You can use timedelta
from datetime import timedelta
str(timedelta(minutes=100))[:-3]
# "1:40"
hours = secs / 3600
minutes = secs / 60 - hours * 60
len = "%d:%02d" % (hours, minutes)
Or, for more recent versions of Python:
hours = secs // 3600
minutes = secs // 60 - hours * 60
len = "%d:%02d" % (hours, minutes)
So len the number of seconds in the movie? That's a bad name. Python already uses the word len for something else. Change it.
def display_movie_length(seconds):
# the // ensures you are using integer division
# You can also use / in python 2.x
hours = seconds // 3600
# You need to understand how the modulo operator works
rest_of_seconds = seconds % 3600
# I'm sure you can figure out what to do with all those leftover seconds
minutes = minutes_from_seconds(rest_of_seconds)
return "%d:%02d" % (hours, minutes)
All you need to do is figure out what minutes\_from\_seconds() is supposed to look like. If you're still confused, do a little research on the modulo operator.
There is a nice answer to this here https://stackoverflow.com/a/20291909/202168 (a later duplicate of this question)
However if you are dealing with timezone offsets in a datetime string then you need to also handle negative hours, in which case the zero padding in Martijn's answer does not work
eg it would return -4:00 instead of -04:00
To fix this the code becomes slightly longer, as below:
offset_h, offset_m = divmod(offset_minutes, 60)
sign = '-' if offset_h < 0 else '+'
offset_str = '{}{:02d}{:02d}'.format(sign, abs(offset_h), offset_m)