Query difference between TimeField and Current Datetime in Django - python

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.

Related

Get Date obj as percentage of that day Python

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.

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

When I substract two datetime object in python it is considering only time not taking day

I have two date time objects
`statrt_time` and `end_time`
my code is
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
total_seconds=diff.seconds
time_diff = (total_seconds/3600.0)
no_of_units = (time_diff/4)
if(e<s):
self.units = 0
else:
self.units = math.ceil(no_of_units)
Here when I subtract time within the same day it is giving the correct difference. But when the day is changed, it is not calculating the day difference but only giving time difference. How can I add day difference also?
Use total_seconds() instead of seconds.
timedelta.seconds just shows "second" part of the difference, while total_seconds() shows the duration of the difference in seconds. See Mureinik's answer for more details.
So, use this:
total_seconds=diff.total_seconds()
total_seconds is a timedelta object which stores the difference between two datetimes using three fields - days, seconds and miliseconds. Your snippet just uses the seconds attributes instead of the entire difference. The total_seconds() method takes care of this for you and returns, well, the total number of seconds between two datatimes.
I got another way of doing.. BUT A WORK AROUND..
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
days=diff.days// convert difference to day instead of seconds//
days_seconds=0
if(days>0): //Checking whether the difference exceeds a day//
days_seconds=days*24*3600 //If so convert it to seconds//
total_seconds=diff.seconds+days_seconds
time_diff = (total_seconds/3600.0)

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.

What is the best way to check if time is within a certain minute?

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

Categories