Minutes and seconds as a variable in Python - python

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'

Related

Convert standard 24 hour format to a range of 99 python

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'

Sleep till next 15 minute hourly interval (00:00, 00:15, 00:30, 00:45)

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)

How do I begin day at 000 using time.strftime() in python 2.7?

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.

What is this exercise meaning in Thinkpython 2e?

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 to get the Seconds of the time using python

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.

Categories