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)
Related
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)
I'm a pretty new python user, working on a project that will be used by people who won't really understand how picky python can be about inputs. For the program, I need to get user input telling me how long a video is(minutes and seconds), and then I need to subtract a minute and eight seconds from that length, then print it. Is there a way I could process an input such as "5 minutes and 30 seconds"?
One possibility is to check each substring in the user's input and assign them to values:
s = input("video length? ")
minutes, seconds = [int(x) for x in s.split() if x.isdigit()]
The cast int(x) will save them as integers if desired:
print(minutes) # 5
print(seconds) # 30
Or a regular expression solution may be:
import re
minutes, seconds = map(int, re.findall('\d+', s))
print(minutes) # 5
print(seconds) # 30
Now you have the values to perform the resulting time calculation:
import datetime
# here, 100,1,1 are just placeholder values for year, month, day that are required to create a datetime object
usertime = datetime.datetime(100,1,1, minute=minutes, second=seconds)
calculation = usertime - datetime.timedelta(minutes=1, seconds=8)
Now you can display the result of the time calculation however you like:
print('{minutes} minutes and {seconds} seconds'.format(minutes=calculation.minute, seconds=calculation.second))
# 4 minutes and 22 seconds
You could use a regular expression if the format will always be the same (but it probably will not), then convert the appropriate string to an integer/ double.
I think that you are going about this incorrectly. It would be best to have two separate input fields that only accept integers. One for minutes and one for seconds. If you want more precision (i.e milliseconds) then just include another input field.
The main problem here is the format in which you will accept the input. You could force the user to input the time in just one format, for example, hours:minutes:seconds, in that case, the code below will calculate the total seconds:
inp = input('Video duration: ').split(':')
hours = 0
mins = 0
secs = 0
if len(inp) >= 3:
hours = int(inp[-3])
if len(inp) >= 2:
mins = int(inp[-2])
secs = int(inp[-1])
total_secs = hours * 3600 + mins * 60 + secs - 68
I oversimplified the code, it doesnt avoid user errors and edge cases
You can try :
import re
from datetime import datetime, timedelta
question = "How long is the video (mm:ss)? "
how_long = input(question).strip()
while not re.match(r"^[0-5]?\d:[0-5]?\d$", how_long): # regex to check if mm:ss digits are in range 0-5
how_long = input("Wrong format. " + question).strip()
mm_ss = how_long.split(":")
how_long_obj = datetime.strptime(f"{mm_ss[0]}:{mm_ss[1]}", '%M:%S')
print(f"{how_long_obj - timedelta(seconds=68):%M:%S}")
Output:
How long is the video (mm:ss)? 22:33
21:25
Python3 Demo - (Please turn Interactive mode On)
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)}")
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.