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.
Related
I need code that will do this:
def foo():
now = datetime.datetime.utcnow()
# Some code will run that takes a variable amount of time
# (less than 15 minutes)
# This code should run no sooner than 15 minutes after `now`
Note that this is not the same as using time.sleep! time.sleep would halt the entire process, but I need computation in foo() to happen and for foo() to return no sooner than 15 minutes after it begins.
You need to calculate the time between the current time and the desired restart time. Then sleep for that amount of time.
wait_time = 15 # minutes
restart_time = datetime.datetime.now() + datetime.timedelta(minutes=wait_time)
# execute code that takes a long time
# for example, let's just sleep for some time
random_time = random.randint(1, wait_time)
time.sleep(random_time * 60)
print("See you again at ", restart_time)
# Now, calculate how long you need to sleep to resume at restart_time
sleep_time = restart_time - datetime.datetime.now()
# Sleep for that amount of time
time.sleep(sleep_time.total_seconds())
print("Hi, I'm back ", datetime.datetime.now())
datetime is not needed, because we do not need to think in human clock terms (hours, minutes, seconds).
All we need is a number of seconds since any fixed moment in the past and time.monotonic does exactly that.
import time
DELAY = 900 # in seconds
start = time.monotonic()
# computation here
end = time.monotonic()
duration = end - start
time.sleep(DELAY - duration)
Last three lines can be written as time.sleep(start + DELAY - time.monotonic()), I split it for simplicity.
import time
import random
import datetime
wait = random.randint(1, 14)
now = datetime.datetime.utcnow()
print(now)
time.sleep(wait * 60)
now = datetime.datetime.utcnow()
print(now)
I think this solves it.
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'
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)
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 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)