I have been trying some code for this, but I can't seem to completely wrap my head around it.
I have a set date, set_date
which is just some random date as you'd expect and that one is just data I get.
Now I would like some error function that raises an error if datetime.now()
is within 24 hours of the set_date
.
I have been trying code with the timedelta(hours=24)
from datetime import datetime, timedelta
now = datetime.now()
if now < (set_date - timedelta(hours=24)):
raise ValidationError('')
I'm not sure whats right to do with this, what the good way to do is. How exactly do I check if the current time is 24 hours before the set date?
To find out if 24 hrs have passed between datetimes in Python, you will need to do some date math in Python. So if you have 2 datetime objects, you'll have to subtract them and then take the timedelta object you get as a result and use if for comparision.
To measure time elapsed during program's execution, either use time. clock() or time. time() functions. The python docs state that this function should be used for benchmarking purposes.
The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Syntax : strftime(format) Returns : It returns the string representation of the date or time object.
now(). time() print(time_in_range(start, end, current)) # True (if you're not a night owl) ;) The code returns True if you run it between (hh:mm:ss) 00:00:00 and 23:55:00 on your computer. Only if you run it between 23:55:00 and 23:59:59 it returns False .
Like that?
if now-timedelta(hours=24) <= set_date <= now:
... #date less than 24 hours in the past
If you want to check for the date to be within 24 hours on either side:
if now-timedelta(hours=24) <= set_date <= now+timedelta(hours=24):
... #date within 24 hours
To check if the date is within 24 hours.
Take a difference between the current time and the past time and check if the no. of days is zero.
past_date = datetime(2018, 6, 6, 5, 27, 28, 369051)
difference = datetime.utcnow() - past_date
if difference.days == 0:
print "date is within 24 hours"
## Also you can check the difference between two dates in seconds
total_seconds = (difference.days * 24 * 60 * 60) + difference.seconds
# Edited. Also difference have in-built method which will return the elapsed seconds.
total_seconds = difference.total_seconds()
You can check if total_seconds is less than the desired time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With