I currently have:
#classmethod
def get_past_week(self):
start_date = datetime.now().date()
end_date = datetime.now().date() - timedelta(weeks=1)
return MyModel.objects.filter(pub_date__range=(end_date, start_date)).aggregate(Sum('off_hours'))
which simply pulls all posts from the current date minus 7 days
I want to pull posts from within the same day factoring in the time at the moment. Thus if the time is 15:00 GMT now, I want all posts from 14:59:49 GMT back to 00:00:01 GMT of the same day. How can I do something like that?
I've tried something like (not work
def get_today_hours(self):
start_time = datetime.now().time()
end_time = datetime.now().time() - timedelta(hours=datetime.today().hour, minutes=0, seconds=0)
return MyModel.objects.filter(pub_date__range=(end_time, start_time))
According to this post on SO, there's a way to get items from same day by using CURDATE()
You can do the following
end_time = datetime.now()
start_time = datetime(end_time.year,end_time.month,end_time.day)
That will set end_time to actual time, and start_time to the same day as end_time, but with the time at 0 hours and 0 seconds.
How about this:
from datetime import datetime, timedelta
end_time = datetime.now()
start_time = datetime.combine(end_time, datetime.min.time()) #Reset the hours/time offset
qs = MyModel.objects.filter(pub_date__range=(start_time, end_time))
Or something even simpler:
qs = MyModel.objects.filter(pub_date__startswith=end_time.date())
Related
I need to make object selections in my database by time interval
currently i found a method to select only objects from a day but not from an interval with this:
data.filter(end_at__day=datetime.datetime.now().day)
I saw this on the django __gte documentation which means from a date until today but I failed to make it work
I have try this:
if request.method == 'POST':
form = DashboardSettingsForm(data=request.POST)
if form.is_valid():
dis_planned = form.cleaned_data.get('display_planned')
dis_currently = form.cleaned_data.get('display_currently')
dis_ended = form.cleaned_data.get('display_ended')
end_at = start_at = datetime.now()
if dis_ended:
end_at = datetime.now() - timedelta(hours=12)
if dis_planned:
start_at = datetime.now() + timedelta(hours=12)
data = data.filter(start_at__gt=start_at, end_at__gt=end_at)
print(f"interval: start{start_at} end{end_at}")
data = data.filter(start_at__gt=start_at, end_at__gt=end_at)
The above line means the objects need to satisfy:
start_ats that are later than datetime.now() - timedelta(hours=12)
end_ats that are later than datetime.now() + timedelta(hours=12)
So you need to use the reverse (lt) for end_at, to make it a filter that covers a range within:
data = data.filter(start_at__gt=start_at, end_at__lt=end_at)
This essentially means the objects need to meet this criteria:
start_ats that are later than datetime.now() - timedelta(hours=12)
end_ats that are earlier than datetime.now() + timedelta(hours=12)
I am new to Python and am having a hard time filtering an api request by datetime: tomorrow basically from hours 0100-2400, only. Time zone is local time. The request prints out as a nested dictionary and I have been able to filter it down to 'validTime' but can't get it filtered anymore from there. My start_time and end_time may be wrong, or my if statement may be wrong, or it's something else. I feel that there is an easy fix for this, I just can't figure it out. Please help. My code is below:
import constants
import requests
import datetime
import json
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
day_after_tomorrow = today + datetime.timedelta(days=2)
hour1 = datetime.time(1, 0, 0)
hour0 = datetime.time(0, 0, 0)
start_time = ['{}T{}+00:00/PT1H'.format(tomorrow, hour1)]
end_time = ['{}T{}+00:00/PT1H'.format(day_after_tomorrow, hour0)]
response = requests.get(constants.austinfgd, headers=headers)
data = json.loads(response.text)
temperature_data = data['properties']['temperature']['values']
print(temperature_data)
This is what is printed out to this point:
Printed response to temperature_data from website
[{'validTime': '2020-12-11T10:00:00+00:00/PT2H', 'value': 17.77777777777778},
{'validTime': '2020-12-11T12:00:00+00:00/PT1H', 'value': 16.666666666666668},
{'validTime': '2020-12-11T13:00:00+00:00/PT2H', 'value': 17.22222222222222},
...
and so on for a number of days
So, now I need to filter by validTime and I specifically want the hours = to and in between start_time and end_time. So, here is my code for that:
for v in temperature_data:
if ['validTime'] >= start_time and ['validTime'] <= end_time:
At this point, pycharm is telling me to simplifiy the chained comparison and it automatically gives me this:
for v in temperature_data:
if start_time <= ['validTime'] <= end_time:
print(v)
At this point, the only thing that prints out is:
Printed response to v
Process finished with exit code 0
I need to print these values by these times only, so I can dump into a table in postgresql, to be used elsewhere.
What am I doing wrong? I have been googling this for over a week, and I give up. Time to ask for help, please help. Thank you in advance for your help.
So, I changed things up and this seems to have worked. Not sure if there is a better way to code this. And I don't understand why I need to have v['validTime'] in the if statement. Is there a cleaner way to do this?
tomorrow = datetime.datetime.combine(
datetime.date.today() + datetime.timedelta(days=1),
datetime.time(1, 0, 0),
tzinfo=pytz.UTC
)
day_after_tomorrow = datetime.datetime.combine(
datetime.date.today() + datetime.timedelta(days=2),
datetime.time(1, 0, 0),
tzinfo=pytz.UTC
)
start_time = tomorrow.isoformat()
end_time = day_after_tomorrow.isoformat()
response = requests.get(constants.austinfgd, headers=headers)
data = json.loads(response.text)
temperature_data = data['properties']['temperature']['values']
for v in temperature_data:
if start_time <= v['validTime'] <= end_time:
print(v)
Good evening, could you help me in how I can put a condition so that a message comes out saying that you can not take an hour because it is already busy ?, I currently have this:
class reserva (models.Model):
_name='gimnasio.reserva'
tipo_reserva=fields.Selection([('clase','Clase'),('evaluacion','Evaluacion')])
fecha_reserva=fields.Date()
start_time=fields.Float()
end_time=fields.Float()
def fecha(self):
if self.star_time==self.star_time:
raise validationError('the hour is busy')
I have another question for you. you know how to configure Datetime only for hour and minutes because I only need hour and minutes but not the date.
To configure Datetime only for hour and minutes.
time = fields.Datetime("time")
custom_time = fields.Char('my_custome_time')
#api.onchange('time')
def _get_time(self):
if self.time:
for rec in self:
# datetime value is a string like 'YYYY-mm-dd HH:MM:SS'
# so just extract string from position 11 to 16
_time = self.time[11:16]
self.custom_time = _time
rec.custom_time = self.custom_time
I think you can use strptime method from datetime module.
from datetime import datetime as dt
start_time = fields.Float()
end_time = fields.Float()
#api.onchange('start_time','end_time')
def _check(self):
records = self.env["gimnasio.reserva"].search([("day", '=', the day you want to check eg. "2019-06-13")])
for rec in records:
ref_start = dt.strptime(str(rec.start_time), "%H:%M")
curr_start = dt.strptime(str(self.start_time), "%H:%M")
if ref_start == curr_start:
raise validationError('the hour is busy')
I didn't debug yet, you can try it.
how to eliminate the default date that you added ("2019-06-13") and that any date should not have the same busy schedule?
In this case you don't need datetime module just
#api.constrains("start_time")
def _check(self):
# search db for any record have same start time.
records = self.env["gimnasio.reserva"].search([('start_time ','=', self.start_time)])
if len(records) > 0:
raise validationError('the hour is busy')
I'd like to make my code a little more user-friendly such that when users post something, i'd like it to say "x seconds/hour/day ago"
so far my code is
{{ post.date_posted.strftime('%Y-%m-%d %H:%M:%S') }}
You want datetime.timedelta()
import datetime
import time
old_time = datetime.datetime.now()
time.sleep(20)
new_time = datetime.datetime.now()
# The below line returns a 'timedelta' object.
delta = new_time - old_time
print('{} seconds have passed.'.format(delta.total_seconds()))
# or
print(
'{} days, {} hours, {} minutes, {} seconds passed.'.format(
delta.days,
delta.seconds//3600,
(delta.seconds//60)%60,
int(delta.total_seconds()%60)))
I believe it also exists for just date and time modules as well.
Say I have a model:
Mymodel(models.Model):
endtimestamp = models.DateTimeField(null=True)
I need a query to get all Mymodel objects with endstimestamp between today's midnight and yesterday midnight.
what have I tried:
today = datetime.datetime.today()
todays_midnigh = datetime.datetime.fromtimestamp(
today.strftime('%Y-%m-%d 00:00:00.0')
)
yesterday_midnight = todays_midnight - datetime.timedelta(days=1)
objs = Mymodel.objects.filter(endtimestamp__range(
yesterday_midnight, todays_midnight)
)
But this line todays_midnigh = datetime.datetime.fromtimestamp(today.strftime('%Y-%m-%d 00:00:00.0')) does not work, and I know there must be a much pythonic and clear way of achieving this.
assumming this from datetime import datetime as dt, do that:
today = dt.today()
todays_midnigh = dt.combine(today,dt.max.time())
or
todays_midnigh = dt.combine(today,dt.min.time())
as appropriate