In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now.
ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, minutes = 55)
market_close = ist_midnight + timedelta(hours=16, minutes = 01)
if ist_time >= market_open and ist_time <= market_close:
check_for_updates()
Any better way of doing this.
This is more compact, but not so obvious:
if '09:55' <= time.strftime(
'%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) <= '16:01':
check_for_updates()
Depending on how important it is for you to do the calculations absolutely properly, you may want to consider daylight saving time (use pytz for that -- it is possible to upload pytz bundled to your app to AppEngine) and seconds and millisecods as well (e.g. use < '16:02' instead of <= '16:01', because the former doesn't depend on the second/subsecond precision.
It seems like you might want datetime's "time" type, which doesn't care about date.
import datetime
ist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30)
# Turn this into a time object (no day information).
ist_time = ist_time.time()
if datetime.time(9, 55) <= ist_time <= datetime.time(16, 1):
...
I'm sure there's a more elegant way to handle the timezone adjustment using tzinfo, but I have to confess I've never dealt with timezones.
Related
I'm given time in millis and I can convert that to date obj with
currentDate = datetime.datetime.fromtimestamp(time_stamp/1000.0).date()
I'm trying to get this time as a percentage of that given day so say its 12:00pm I'd like to get 50% as output.
Here's my attempt
currentDate = datetime.datetime.fromtimestamp(time_stamp/1000.0).date()
NextDay_Date = currentDate + datetime.timedelta(days=1)
start_of_next_day=NextDay_Date.replace(hour=00, minute=00)
difference=start_of_next_day.timestamp()*1000 -currentDate.timestamp()*1000
milis_in_a_day=86400000
percent_of_day=difference/milis_in_a_day
There has to be a more elegant solution.
You could just count the number of microseconds passed today, by just using the time part of the date.
from datetime import datetime
today = datetime.now()
microseconds_today = (
(
(
(today.hour * 60) + today.minute
) * 60 + today.second
) * 1_000_000 + today.microsecond
)
print(microseconds_today / 86_400_000_000)
You're basically on the right path, only thing I could think of to be a bit more "readable" is to use timedelta from datetime. Note the fully qualified names used below - datetime in particular can be a bit confusing to read, definitely suggest referencing the documentation: https://docs.python.org/3/library/datetime.html
import datetime
TOTAL_DAY_SECS = 86400.0
def timedelta_percentage(input_datetime):
d = input_datetime - datetime.datetime.combine(input_datetime.date(), datetime.time())
return d.total_seconds() / TOTAL_DAY_SECS
now = datetime.datetime.now()
print(f"'datetime.now()': {now}")
answer = round(timedelta_percentage(now) * 100, 2)
print(f"Percentage of day complete, based on 'now': {answer}%")
Output:
'datetime.now()': 2021-04-23 09:38:16.026000
Percentage of day complete, based on 'now': 40.16%
You could certainly adapt this to be more precise using microseconds, depending how granular of an answer you need.
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?
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
It is as simple as that:
from datetime import datetime
#...some code...
if (datetime.now() - pastDate).days > 1:
print('24 hours have passed')
else:
print('Date is within 24 hours!')
What you do here is subtract the old date pastDate from the current date datetime.now(), which gives you a time delta datetime.timedelta(...) object. This object stores the number of days, seconds and microseconds which have passed since the old date.
That will do:
if now - timedelta(hours=24) <= set_date <= now + timedelta(hours=24):
#Do something
Which is equivalent to:
if now - timedelta(hours=24) <= set_date <= now or now <= set_date <= now + timedelta(hours=24):
# ---^--- in the past 24h ---^--- in the future 24h
#Do something
I'm trying to pick values from Django a model where the difference between validity field, which is a DateTimeField, and the current time should be lesser than 10 minutes.
For that I tried:
now = datetime.datetime.now()
now_plus_10 = now + datetime.timedelta(minutes = 10)
slots_bookings = Table.objects.filter(validity__lte=now_plus_10)
However, this will always give me a any value that's lesser than 10 minutes from now which can include timestamps from even more than the 10 minute window.
I'm trying to figure if there's a way I can get the fields where
current_time - validity <= 10 minutes
How do I go about this?
now = datetime.datetime.now()
delta = datetime.timedelta(minutes=10)
now_plus_10 = now + delta
now_minus_10 = now - delta
Tables.objects.filter(validity__gte=now_minus_10, validity__lte=now_plus_10)
You may use django.utils.timezone.now instead of datetime.datetime.now if you use timezones.
I want to write a simple python script which will check to see if it's 2 minutes before a given hour/minute, and then call my function either everyday or for a given date at the given time.
The script will run every minute in a cronjob.
So the two cases to execute myfunction():
10:55 everyday
10:55 on 9/28/2012
But I am having trouble determining when it's 2 minutes prior to the given hour/minute using datetime. Also, how to determine everyday vs just on a given day?
mydate = datetime(2012, 09,28, 10,55)
check = mydate - datetime.now() # gives you a timedelta
if check < datetime.timedelta(minutes=2):
run_myfunction()
The above sees if it's within 2 minutes, and if it is, then runs the myfunction(). The problem with the above code is that if the mydate has passed, the myfunction() will still run. Also, this requires that a specific date to be specified. How would one allow the check for everyday rather than 9/28/2012?
now = datetime.now()
mystart = now.replace(hour=10, minute=55, second=0)
myend = mystart + timedelta(minutes=2)
if mystart <= mydate < myend:
# do your stuff
Change your code like this
mydate = datetime(2012, 09,2, 10,55)
current_date = datetime.now()
check = mydate - current_date # gives you a timedelta
if mydate > current_date and check < datetime.timedelta(minutes=2):
run_myfunction()
It may be hackish, but you can use .total_seconds() to construct a range:
from datetime import datetime, timedelta
then = datetime(2012, 9, 18, 16, 5)
now = datetime.now()
delta = timedelta(minutes=10)
if 0 < (then - now).total_seconds() < delta.total_seconds():
# ...
That way, if then - now is a negative timedelta, total_seconds() will return a negative number and make your condition False.
For the everyday part, you can use
reference = datetime.datetime(2012,9,18,23,55,00)
now = datetime.datetime.now()
today = reference.replace(year=now.year,month=now.month,day=now.day)
For the time difference:
delta = (now-today)
lapse = delta.days * 86400 + delta.seconds
if abs(lapse) <= 2*60:
run_function()
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:
if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes
This generates a type error.
What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison.
Please post lists of datetime best practices.
Use the datetime.timedelta class:
>>> from datetime import datetime, timedelta
>>> then = datetime.now() - timedelta(hours = 2)
>>> now = datetime.now()
>>> (now - then) > timedelta(days = 1)
False
>>> (now - then) > timedelta(hours = 1)
True
Your example could be written as:
if (datetime.now() - self.timestamp) > timedelta(seconds = 100)
or
if (datetime.now() - self.timestamp) > timedelta(minutes = 100)
Compare the difference to a timedelta that you create:
if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):
print 'older'
Alternative:
if (datetime.now() - self.timestamp).total_seconds() > 100:
Assuming self.timestamp is an datetime instance
You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:
def seconds_difference(stamp1, stamp2):
delta = stamp1 - stamp2
return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.
Use abs() in the answer if you always want a positive number of seconds.
To discover how many seconds into the past a timestamp is, you can use it like this:
if seconds_difference(datetime.datetime.now(), timestamp) < 100:
pass
You can subtract two datetime objects to find the difference between them.
You can use datetime.fromtimestamp to parse a POSIX time stamp.
Like so:
# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
print "object is over 100 seconds old"
Convert your time delta into seconds and then use conversion back to hours elapsed and remaining minutes.
start_time=datetime(
year=2021,
month=5,
day=27,
hour=10,
minute=24,
microsecond=0)
end_time=datetime.now()
delta=(end_time-start_time)
seconds_in_day = 24 * 60 * 60
seconds_in_hour= 1 * 60 * 60
elapsed_seconds=delta.days * seconds_in_day + delta.seconds
hours= int(elapsed_seconds/seconds_in_hour)
minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)
print("Hours {} Minutes {}".format(hours,minutes))