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'
Related
I need my script to sleep till the next 15 minute hourly interval, e.g. on the hour, quarter past, half past, and quarter too.
It will look something like this
While True:
//do something
sleepy_time = //calculate time to next interval
time.sleep(sleepy_time)
You could write a series of if statements to check what the current minutes past the hour is then do ‘if current < 15’ and ‘if current < 30’ etc but that seems messy and inefficient.
EDIT: Building on #martineau's answer this is the code I went with.
import datetime, time
shouldRun = True
if datetime.datetime.now().minute not in {0, 15, 30, 45}:
shouldRun = False
# Synchronize with the next quarter hour.
while True:
if shouldRun == False:
current_time = datetime.datetime.now()
seconds = 60 - current_time.second
minutes = current_time.minute + 1
snooze = ((15 - minutes%15) * 60) + seconds
print('minutes:', minutes, 'seconds', seconds, ' sleep({}):'.format(snooze))
localtime = time.asctime( time.localtime(time.time()))
print("sleeping at " + localtime)
time.sleep(snooze) # Sleep until next quarter hour.
shouldRun = True
else:
localtime = time.asctime( time.localtime(time.time()))
print("STUFF HAPPENS AT " + localtime)
shouldRun = False
The difference between his answer and this is that this run the else block only once per interval then if the minute is still on the 0, 15, 30, 45 interval calculates the extra seconds to add to the minutes to sleep till the next interval.
You can achieve this using datetime...
A call to datetime.datetime.now() will return a datetime which you can get the current minute past the hour with .minute.
Once we have the number of minutes past the hour, we can do that modulo 15 to get the number of minutes to the next interval of 15.
From here, simply do a call to time.sleep() with that number of minutes times 60 (60 seconds in a minute).
The code for this may look something like:
import datetime, time
minutesToSleep = 15 - datetime.datetime.now().minute % 15
time.sleep(minutesToSleep * 60)
print("time is currently at an interval of 15!")
time.sleep(15*60 - time.time() % (15*60))
15*60 is a numer of seconds in every 15 mins.
time.time() % (15*60) would be the number of seconds passed in the current 15 min frame (since time 0 is 00:00 by definition). It grows from 0 at XX:00, XX:15, XX:30, XX:45, and up to 15*60-1 (actually, 15*60-0.(0)1 — depends on the precision of time measurements), and then starts to grow from 0 again.
15*60 - time.time() % (15*60) is the number of seconds left till the end of the 15-min frame. It, with a basic math, decreases from 15*60 to 0.
So, you need to sleep that many seconds.
However, keep in mind that sleep will not be very precise. It takes some time to process the internal instructions between time.time() is measured, and time.sleep() is actually called on the system level. Nano-fractions of a second, probably. But in most cases it is acceptable.
Also, keep in mind that time.sleep() does not always sleeps for how long it was asked to sleep. It can be waked up by signals sent to the process (e.g., SIGALRM, SIGUSR1, SIGUSR2, etc). So, besides sleeping, also check that the right time has been reached after time.sleep(), and sleep again if it was not.
I don't think #Joe Iddon's answer is quite right, although it's close. Try this (note I commented-out lines I didn't want running and added a for loop to test all possible values of minute):
import datetime, time
# Synchronize with the next quarter hour.
#minutes = datetime.datetime.now().minute
for minutes in range(0, 59):
if minutes not in {0, 15, 30, 45}:
snooze = 15 - minutes%15
print('minutes:', minutes, ' sleep({}):'.format(snooze * 60))
#time.sleep(snooze) # Sleep until next quarter hour.
else:
print('minutes:', minutes, ' no sleep')
import time
L = 15*60
while True:
#do something
#get current timestamp as an integer and round to the
#nearest larger or equal multiple of 15*60 seconds, i.e., 15 minutes
d = int(time.time())
m = d%L
sleepy_time = 0 if m == 0 else (L - m)
print(sleepy_time)
time.sleep(sleepy_time)
import schedule
import time
# Define a function named "job" to print a message
def job():
print("Job is running.")
# Set the interval for running the job function to 15 minutes
interval_minutes = 15
# Loop over the range of minutes with a step of interval_minutes
for minute in range(0, 60, interval_minutes):
# Format the time string to be in the format of "MM:SS"
time_string = f"{minute:02d}:00" if minute < 60 else "00:00"
# Schedule the job function to run at the specified time every hour
schedule.every().hour.at(time_string).do(job)
# Infinite loop to keep checking for any pending job
while True:
schedule.run_pending()
# Sleep for 1 second to avoid high CPU usage
time.sleep(1)
I'm doing a calculation that returns the total number of seconds. Then I turn that into days, hours, minutes, seconds using python time.strftime()
total_time = time.strftime("%-j days, %-H hours, %-M minutes, %-S seconds,", time.gmtime(total_seconds))
But, using %-j begins on 001, so my calculation is always off by 1 day. Is there a way to start %-j on 000? Is there a better way to do this? Thanks!
This seems like an extremely convoluted way to get days, hours, minutes and seconds from a total seconds value. You can just use division:
def secs_to_days(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return (days, hours, minutes, seconds)
total_time = ("{:03} days, {:02} hours, {:02} minutes, "
"{:02} seconds,").format(*secs_to_days(total_seconds))
To handle the pluralisation of these (001 day instead of 001 days), you can modify the helper function to do it.
def secs_to_days(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
seconds = "{:02} second{}".format(seconds, "" if seconds == 1 else "s")
minutes = "{:02} minute{}".format(minutes, "" if minutes == 1 else "s")
hours = "{:02} hour{}".format(hours, "" if hours == 1 else "s")
days = "{:03} day{}".format(days, "" if days == 1 else "s")
return (days, hours, minutes, seconds)
total_time = ", ".join(secs_to_days(seconds))
If you handle plurals often, see Plural String Formatting for the geneal case.
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)}")
How can I store hours/minutes/seconds as variable in python?
For example:
time = "01:30" # 1 minute and 30 seconds
time2 = time + 10 seconds
Basically a program (using FFMPEG) will decide when to start playing an audio file but the value can be changed in +-10 seconds. The questions is how can I store this value?
To clarify my question:
The time variable is "01:30" which clearly represent the time, 01 min 30 seconds. How can I add 10 seconds to it to make the variable 10:40? Clearly 01:30+:00:10 is not the solution.
Store time as an integer representiong seconds only, then format that to the ffmpeg time duration format with a simple function:
def format_duration(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
Demo:
>>> def format_duration(seconds):
... minutes, seconds = divmod(seconds, 60)
... hours, minutes = divmod(minutes, 60)
... return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
...
>>> duration = 170
>>> format_duration(duration)
'00:02:50'
>>> duration += 10
>>> format_duration(duration)
'00:03:00'
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)