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)}")
Related
I have a python program which I want to execute exactly 30 seconds before every 5th Minute and need to run for 30 seconds only.
Rather than looping and testing if it's the right time over and over again, it's better to calculate the amount of time needed to wait, and sleep until then so the processor can go off and do other things. To do this we still use the datetime module and just a bit of simple math.
from datetime import datetime as dt
from time import sleep
#Calculating sleep interval
t = dt.now()
#seconds in the hour
sec = t.second + t.minute*60
#seconds since the last 5 min interval
sec = sec % 300
#until the next 5 min interval
sec = 300 - sec
#30 sec before that
sec = sec - 30
#if negative we're within 30 sec of 5 minute interval so goto next one
if sec < 0:
sec = sec + 300
sleep(sec)
while True: #loop forever
#with a little re-arranging and boolean math, this can all be condensed to:
t = dt.now()
s = (t.second + 60*t.minute) % 300
sleep(270 - s + 300 * (s >= 270))
#yourFunction()
For very simple cases this should work. If at any point your program crashes, or if the computer re-boots, or a myriad of other reasons, It would be better to use something built in to the OS which will re-start the program automatically, and can handle other conditions such as setting sleep timers, or only executing if a particular user is logged in. On Windows this is task scheduler, on Linux this is typically cron, and OSX is launchd (at least according to developer.apple.com)
If you're running this code indefintley, I'd suggest you look at following Aaron's adivce at look at superuser.com, apple.stackexchange.com or askubuntu.com.
However, if you were going to write this in Python, you could use the datetime module and find the time that's elapsed.
from datetime import datetime
import time
def your_function(t1):
i = 0
# For the next 30 seconds, run your function
while (datetime.now() - t1).seconds =< 30:
i += 1
print(i)
time.sleep(1)
# Run indefintely
while True:
# Record the current time
t1 = datetime.now()
while t1:
# Find the elapsed time in seconds
# If the difference is 270 seconds (4 minutes and 30 seconds)
if (datetime.now()-t1).seconds == 270:
your_function(t1)
# Remove t1 and start at the top of the loop again
t1 = None
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'm suppose to write a code to give me the output of a value between 0 and 86400 and the current time in the 24 hour clock. However I am getting stuck when it comes to writing the formulas for the 24 hour clock and the print function. Here's the code I have written so far.
total_time = float('70000')
hours = int(total_time / 3600.0)
minutes = int((total_time - (hours * 3600.0)) / 60.0)
seconds = int(((total_time) - (hours * 3600) - (minutes * 60)))
print("Enter a value between 0 and 86400", total_time) print("The current time is",hours.minutes.seconds)
Firstly, get the current hour, minute and seconds:
import datetime
now = datetime.datetime.now()
# The current time:
hour = now.hour
minute = now.minute
second = now.second
Then simply output it:
print("Current time: {}:{}:{}".format(hour,minute,second))
It seems to me you are asking the user to enter a number between 0 and 86400 and then you want to translate that to hh:mm:ss format. But your code is not getting any input from the user, and the last line of the code has syntax errors.
To get you started, you need to fix your print() calls at the end. Put one statement to a line, and use commas not fullstops:
print("Enter a value between 0 and 86400", total_time)
print("The current time is",hours,minutes,seconds)
That will give you the output:
Enter a value between 0 and 86400 70000.0
The current time is 19 26 40
Which is correct, in the sense that an offset of 70,000 seconds from 0h00 today is 19h26m40s.
If you want to get actual user input, then you need to ask for it, at the top of your program, before you do the calculations, in an input() call:
total_time=float(input("Enter a value between 0 and 86400: "))
If you want pretty formatting of the answer then do
print(f"The current time is {hours:02d}:{minutes:02d}:{seconds:02d}")
None of this relates to finding the current time, which Suraj Kothari's answer addresses.
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)
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.