Flask-sqlalchemy filter by unix interval - python

I store the created_at column as a unix integer on my Post table. I need to filter all posts that have a created_at unix timestamp that is between 23h59 and 24h00 old, from the start of that specific day.
In other words, I need to filter all of the posts that are in their last minute of that that 24h interval since they have been created.
This query works for posts that are less than a day old
post_min = now - 86400
post_max = now - 86400 + 60
posts = Post.query.filter(Post.created_at >= post_min, Post.created_at < post_max).all()
How do I do this for posts that are older than a day?

You can use modulo arithmetic:
(now % (60 * 60 * 24)) >= (60 * 60 * 24 - 60)
This spells out the multiplication. You can of course write this as:
(now % 86400) >= (86400 - 60)
It might not be obvious to most people (or even you in the future) that 60*60*24 = 86400.

Related

Python check if date is within 24 hours

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

calculate difference between two time in hour

I want to calculate difference between two time in hours using django in sql db the time are stored in timefield.
I tried this:
def DesigInfo(request): # attendance summary
emplist = models.staff.objects.values('empId', 'name')
fDate = request.POST.get('fromDate')
tDate = request.POST.get('toDate')
if request.GET.get('empId_id'):
sel = attendance.objects.filter(empId_id=request.GET.get('empId_id'),)
for i in sel:
# print i.
# print i.outTime
# print i.inTime.hour,i.inTime.minute,i.inTime.second - i.outTime.hour,i.outTime.minute,i.outTime.second
ss = i.inTime.hour
ss1 = 12 - ss
mm = i.outTime.hour
mm1 = (12 + mm) - 12
print ss1 + mm1
Since i.inTime and i.outTime are time objects you cannot simply subtract them. A good approach is to convert them to datetime adding the date part (use today() but it is irrelevant to the difference), then subtract obtaining a timedelta object.
delta = datetime.combine(date.today(), i.outTime) - datetime.combine(date.today(), i.inTime)
(Look here: subtract two times in python)
Then if you want to express delta in hours:
delta_hours = delta.days * 24 + delta.seconds / 3600.0
A timedelta object has 3 properties representing 3 different resolutions for time differences (days, seconds and microseconds). In the last expression I avoided to add the microseconds but I suppose it is not relevant in your case. If it is also add delta.microseconds / 3600000000.0
Note that simply dividing seconds by 3600 would have returned only the integer part of hours avoiding fractions. It depends on your business rules how to round it up (round, floor, ceil or leave the fractional part as I did)
Using datetime objects: https://docs.python.org/2/library/datetime.html
A good stack overflow post on the topic How to get current time in Python
from datetime import datetime
now = datetime.now()
# wait some time
then = ... some time
# diff is a datetime.timedelta instance
diff = then - now
diff_hours = diff.seconds / 3600
You might want to play with this codes:
from datetime import datetime
#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"
#convert string to actual date and time
time1 = datetime.strptime('8-01-2008 00:00:00', date_format)
time2 = datetime.strptime('8-02-2008 01:30:00', date_format)
#find the difference between two dates
diff = time2 - time1
''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')
#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');
''' now print only the time difference '''
''' between two times (date is ignored) '''
print ('\nTime difference between two times (date is not considered)')
#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600
hours = (diff.seconds) / 3600
print (str(hours) + ' Hours')
#same for minutes just divide the seconds by 60
minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')
#to print seconds, you know already ;)
print (str(diff.seconds) + ' secs')
The easiest way through I achieve is the comment of Zac given above. I was using relativedelta like this
from dateutil import relativedelta
difference = relativedelta.relativedelta( date1, date2)
no_of_hours = difference.hours
but it did not give me correct result when the days changes. So, I used the approach expressed above:
no_of_hours = (difference.days * 24) + (difference.seconds / 3600)
Please note that you will be getting negative value if date2 is greater than date1. So, you need to swipe the position of date variables in relativedelta.

Query difference between TimeField and Current Datetime in Django

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.

call function between time intervals

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.

Python Date Comparisons

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))

Categories