I'm currently using a REST API that only allows 1000 queries per hour
Once the 1000 queries are used up, you then have to wait until the beginning of the next hour for the counter to be reset
My aim is to determine the number of seconds that I have to wait until the start of the next hour
I'm currently using the time.sleep method to put the script to sleep until the start of the next hour
I've put together a rather crude solution as follows using the datetime library (adding two minutes to be safe)
import datetime
# Determine the seconds until the next hour (add 2 minutes to be safe)
now = datetime.datetime.now()
next_hour = datetime.datetime(now.year, now.month, now.day, now.hour + 1, 2)
sleep_seconds = (next_hour - now).seconds
# Put the execution to sleep for a while
print("Sleeping for {0} minutes...".format(sleep_seconds // 60))
time.sleep(sleep_seconds)
This script does work but is unreliable when the next hour is the start of the next day.
datetime expects hour values between 0..23
If the
datetime.datetime.now() method returned 23 the method would fail
if you pass 24 to the datetime object
It would also be unreliable if the next day crossed into the next month or year as well.
Could someone suggest a better solution that would account for these wrap around issues?
Think datetime.timedelta will help you in this case. Something like this:
import datetime
delta = datetime.timedelta(hours=1)
now = datetime.datetime.now()
next_hour = (now + delta).replace(microsecond=0, second=0, minute=2)
wait_seconds = (next_hour - now).seconds
The replace should work to round you down to the next hour.
Related
So I have a datetime.datetime object and I want to compute the next minute of it. What I mean by next minute is the same time but at the very beginning of the next minute. For example, the next minute of 16:38:23.997 is 16:39:00.000.
I can do that easily by adding 1 to the minute and setting every smaller values to 0 (seconds, milliseconds, etc), but I'm not satisfied with this way, because I may need to carry out by checking if the minute becomes higher than 60, and if the hour is bigger than 24... and it ends up being over complicated for what I want to do
Is there a "simple" pythonic way to achieve this ?
Yes, there is a simple and Pythonic way to achieve this. You can use the datetime.replace method to change only the values you want, and leave the others unchanged. Here's an example:
from datetime import datetime, timedelta
def next_minute(dt):
return dt.replace(microsecond=0, second=0) + timedelta(minutes=1)
You can use this function to get the next minute of a datetime object by passing it to the function next_minute(dt). This function first sets the microsecond and second values to 0 using the replace method, and then adds a timedelta of 1 minute to get the next minute.
example:
from datetime import datetime, timedelta
def next_minute(dt):
return dt.replace(microsecond=0, second=0) + timedelta(minutes=1)
current_time = datetime.now()
print("Current time:", current_time)
ext_minute_time = next_minute(current_time)
print("Next minute:", next_minute_time)
#Output
Current time: 2022-02-07 11:38:23.997
Next minute: 2022-02-07 11:39:00
I have a piece of code, which takes inputs in 24 hour time such as 23:59, and prints how much time is left, so if it was 11:59 in the morning, it would return 12 hours.
I have been able to do this so far, but I cannot tell what is going wrong with this code right now:
from datetime import datetime
def timeuntil(t):
time = t
future = datetime.strptime(time, '%H:%M').replace(day = datetime.now().day, year = datetime.now().year, month = datetime.now().month)
timeleft = (future - datetime.now())
return timeleft
For your reference, print(timeuntil(22:00)) returned 15:55:01.996377 when I ran it at 8:43 PM.
Thanks for your help.
The issue does not seem reproducible on my machine, even when defining the datetime objects to the time you specified. However It could be to do with replace() on your datetime.
There is really no need for this, and I think you would be best to create a datetime object correctly. Below addresses the problem and works as you have intended.
def timeuntil(begin):
hour, minute = map(int, begin.split(':'))
now = datetime.now()
future = datetime(now.year, now.month, now.day, hour, minute)
return (future - now)
print(timeuntil("23:59"))
#7:35:06.022166
If you want to specify a different timezone to run this in, we can define our datetime.now() with a timezone, however we will need to strip this off to calculate future - now.
def timeuntil(begin):
hour, minute = map(int, begin.split(':'))
now = datetime.now(timezone('US/Pacific')).replace(tzinfo=None)
future = datetime(now.year, now.month, now.day, hour, minute)
return (future - now)
I believe you want the number of seconds until you reach the next day. I find this easier to follow with the time module and direct calculations.
import time
secs_in_day = 60*60*24
secs_time_left_local = secs_in_day - (time.time() - time.altzone) % secs_in_day
hours = int(secs_time_left_local // 3600)
minutes = int((secs_time_left_local % 3600) // 60)
seconds = int((secs_time_left_local % 3600) % 60)
print(f'{hours:02}:{minutes:02}:{seconds:02}')
Say I have this time
00:46:19,870
where it represents 46h 19m and 870 is 870/1000 of a minute (I think I can just get rid of the last part). How do I convert this to seconds?
I've tried
time.strptime('00:46:19,870'.split(',')[0],'%H:%M:%S')
but realized that it wouldn't work as it's using a format different than mine.
How can I convert 00:46:19,870 to 2779?
You are close, you can still use the datetime you just need to calculate the time delta. What you really have isn't really a date but what appears to be a stopwatch time time. You can still strip the time from that and you will notice that Python uses a default year, month, and day. You can use that default to figure out the delta in seconds:
from datetime import datetime
DEFAULT_DATE = (1900, 1, 1)
stopwatch = datetime.strptime('00:46:19,870', '%H:%M:%S,%f')
a_timedelta = stopwatch - datetime(*DEFAULT_DATE)
seconds = a_timedelta.total_seconds()
print(seconds)
So I'm using an API that requires time in Unix and 2 integers, one for the start time and one for the end time.
I'm trying to make it so that the start time is one minute ago and that my end time is now.
I've already writhen the end time but I can't get the start time.
Code:
while True:
temps = int(time.time())
temps1 = int(time.time())
print(temps)
print(temps1)
qty = 1
r = requests.get(f'https://finnhub.io/api/v1/indicator?symbol={symbol}&resolution=5&from={temps1}&to={temps}&indicator=rsi&timeperiod=1&token=c0e6j5n48v6s9jus1ejg')
e = list(r.json().values())
time.time() - 60
or
endtime - 60
I need to find the Time which is an hour head of current system time in python, for example if current time is 2:00 the end time should be 3:00 so that i can compare that my current time is within the range of the time period.Actually I need to carry out a task only during the time period ,So can someone help me!
Use datetime.now() to get the current time, save it, call datetime.now() again when you need to check the time and subtract it by the starting time to get a timedelta to check if it's less than 1 hour:
from datetime import datetime, timedelta
start = datetime.now()
while datetime.now() - start <= timedelta(hours=1):
do_work()
#blhsing is a good answer but there is a simpler and cost-effective way:
import time
end = time.clock() + 3600 # add hour
while time.clock() < end:
...