Current time within the range - python

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:
...

Related

How to compute the next minute of a time in Python?

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

Apply a datetime to a file but for 1 day in the past

Does anyone know how I can apply a date one day in the past as my filename? With this code, it would give me a file name of 'File09202021161235.csv' however I would like this to output 1 day in the past.
'File' + datetime.datetime.today().strftime('%m%d%Y%H%M%S''.csv')
I tired using timedelta(days=1) but then the strftime breaks? Can anyone offer any guidance?
It's very simple. First of all you are doing it wrong.
datetime.timedelta(days=1)
It's only the time for 1 days. It's not a current time. It's an interval.
The fix is you need to subtract the this 1 days time interval from current time.
import datetime
#Here we are subtracting the current time with 1 days time interval
past_day = datetime.datetime.today() - datetime.timedelta(days=1)
your_file_name = 'File' + past_day.strftime('%m%d%Y%H%M%S''.csv')

Python how to get current time as an integer

This is my code that I tried to use but it doesn't work since it's a string
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
print("time=", current_time)
wake_up=0
x=current_time - wake_up - 0.40
wake_up = float(input("when are you gonna wake up"))
print(x)
I am trying to make a calculator where as it prints the current time. (for example 23:00) and then the input asks what time are you going to wake up and you write (for example 08:30) and the output should be "You will get 09:30 hours and minutes of sleep" or preferably "You will get 9 hours and 30 minutes of sleep"
I tried to do this but it is a string and cannot be calculated and I tried to find an integer version of the now.strftime module. Can someone help me find out how to do this?
You'll need to use datetime.strptime(), which takes in a date string and a format string (reference here) and converts the string to a datetime object.
In your case, you would use the following to convert wake_up to a datetime object:
dt = datetime.strptime(wake_up, "%H:%M")
Modifications done based on your code:
from datetime import datetime, date
now_time = datetime.now().time() # get time only
current_time_str = now.strftime("%H:%M")
print("time=", current_time_str)
#wake_up = input("when are you gonna wake up")
wake_up = '08:30' # assuming this is user input
wake_up_time = datetime.strptime(wake_up, "%H:%M").time()
x = datetime.combine(date.today(), wake_up_time) - datetime.combine(date.today(), now_time)
print(str(x)) #also, you can get hours by x.seconds/3600
Other questions will help you.
Python speed testing - Time Difference - milliseconds
Converting string into datetime
subtract two times in python
Format timedelta to string

Get number of seconds until the start of the next hour

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.

How do you setup simple timer between two times when the other time is the next day?

Python noob here
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(10,30) and now_time <= time(13,30):
print "yes, within the interval"
I would like the timer to work between 10,30 AM today and 10 AM the next day. Changing time(13,30) to time(10,00) will not work, because I need to tell python 10,00 is the next day. I should use datetime function but don't know how. Any tips or examples appreciated.
The combine method on the datetime class will help you a lot, as will the timedelta class. Here's how you would use them:
from datetime import datetime, timedelta, date, time
today = date.today()
tomorrow = today + timedelta(days=1)
interval_start = datetime.combine(today, time(10,30))
interval_end = datetime.combine(tomorrow, time(10,00))
time_to_check = datetime.now() # Or any other datetime
if interval_start <= time_to_check <= interval_end:
print "Within the interval"
Notice how I did the comparison. Python lets you "nest" comparisons like that, which is usually more succinct than writing if start <= x and x <= end.
P.S. Read https://docs.python.org/2/library/datetime.html for more details about these classes.
Consider this:
from datetime import datetime, timedelta
now = datetime.now()
today_10 = now.replace(hour=10, minute=30)
tomorrow_10 = (now + timedelta(days=1)).replace(hour=10, minute=0)
if today_10 <= now <= tomorrow_10:
print "yes, within the interval"
The logic is to create 3 datetime objects: one for today 10 AM, one for right now and one for tomorrow 10 AM. Them simply checking for the condition.
An alternative to creating time objects for the sake of comparison is to simply query the hour and minute attributes:
now= datetime.now().time()
if now.hour<10 or now.hour>10 or (now.hour==10 and now.minute>30):
print('hooray')

Categories