Get items for the last few hours - python

In the model there is a field DateTimeField(), the database stores the value of the form 2015-09-21 17:37:11. How to make a selection, for the last several hours. For example, in the sample were only the values for the last 3 hours.

You need to build the date reference manually, and use it in the query.
from datetime import datetime, timedelta
now = datetime.now()
before = now - timedelta(hours=3)
qs = MyModel.objects.filter(date__gte=before)
As a reference, the datetime module.
Note that if you use locale-aware times in your application (through USE_TZ=True setting), you will need to change the way you get current time to this:
from django.utils import timezone
now = timezone.now()

Try:
from datetime import datetime, timedelta
delta = datetime.now() - timedelta(hours=3)
Model.objects.filter(date_time__gte=delta)

Related

How to add time to a time string

I would like to add a certain time to a formatted time string in python. For this I tried the following
from datetime import datetime, timedelta
timestemp_Original = '2021-07-13T00:15:00Z'
timestemp_Added1 = '2021-07-13T00:15:00Z' + timedelta(minutes=15)
timestemp_Added2 = timestemp_Original + datetime.timedelta(hours=0, minutes=15)
but this leads to error messages (I took it from here How to add hours to current time in python and Add time to datetime). Can aynone tell me how to do this?
First, You need to convert str to datetime with a specific format of string_date and then use timedelta(minutes=15).
from datetime import datetime, timedelta
timestemp_Original = '2021-07-13T00:15:00Z'
timestemp_Added1 = datetime.strptime(timestemp_Original, "%Y-%m-%dT%H:%M:%SZ") + timedelta(minutes=15)
print(timestemp_Added1)
# If you want to get as original format
print(timestemp_Added1.strftime("%Y-%m-%dT%H:%M:%SZ"))
# 2021-07-13T00:30:00Z
2021-07-13 00:30:00

How to append GMT+ to datetime object in python

I have a datetime filed in my models.py and another field that saves the selected timezone as well (like Asia/Tehran).
I need to append the the utc info of this timezone to my datetime object like this:
'20/4/2021 18:33:00 Gmt+4:30
How can i do that?
Use this code, replace the numbers with your specified date in your GMT+4.5 timezone.
import datetime
timezone_diff = datetime.timedelta(hours=4.5)
GMT_timezone = datetime.timezone(timezone_diff, name="GMT")
GMT_time = datetime.datetime(2017,2,14,12,15,1,99,GMT_timezone,fold=1)
print('{0:%d}/{0:%m}/{0:%Y} {0:%H:%M:%S} {0:%Z}{0:%z}'.format(GMT_time))
See results:

How to minus time that received from API server and current time in Python

Kindly help below my query:
I got an estimated time from API server like below:
2019-09-25T20:11:23+08:00
it seems like iso 8601 standard with timezone.
I would like to know how to calculate how many days, hours, minutes and seconds left from above value to the current time.
import datetime
Receved_time_frim_API = "2019-09-25T20:11:23+08:00"
Current_time = datetime.datetime.now()
left_days =
left_hour =
left_min =
left_sec =
Your time string contains timezone info. According to https://stackoverflow.com/a/13182163/12112986 it's easy to convert it to datetime object in python 3.7
import datetime
received = datetime.datetime.fromisoformat(Receved_time_frim_API)
In previous versions there is no easy oneliner to convert string with timezone to datetime object. If you're using earlier python version, you can try something crude, like
>>> date, timezone = Receved_time_frim_API.split("+")
>>> tz_hours, tz_minutes = timezone.split(":")
>>> date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
>>> date -= datetime.timedelta(hours=int(tz_hours))
>>> date -= datetime.timedelta(minutes=int(tz_minutes))
Note that this will work only in case of positive timezones
To substract two datetime objects use
td = date - Current_time
left_days = td.days
left_hour = td.seconds // 3600
left_min = (td.seconds//60)%60
left_sec = td.seconds % 60
Okay first you need to parse the Receved_time_frim_API into datetime format:
from dateutil import parser
Receved_time_frim_API = parser.parse("2019-09-25T20:11:23+08:00")
But you can't just substract this from your Current_time, because datetime.now() is not aware of a timezone:
from datetime import timezone
Current_time = datetime.datetime.now().replace(tzinfo=timezone.utc)
print (Current_time-Receved_time_frim_API)
The result is a datetime.timedelta

How to add a certain time to a datetime?

I want to add hours to a datetime and use:
date = date_object + datetime.timedelta(hours=6)
Now I want to add a time:
time='-7:00' (string) plus 4 hours.
I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.
Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object
input_time = datetime.strptime(yourtimestring,'yourtimeformat')
input_seconds = input_time.second # for seconds
input_minutes = input_time.minute # for minutes
input_hours = input_time.hour # for hours
# Usage: input_time = datetime.strptime("07:00","%M:%S")
Rest you have datetime.timedelta method to compose the duration.
new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)
See docs strptime
and datetime format
You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.
Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.
dt.time() prints out the result you were looking for.
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()
Edit:
To get from a string time='7:00' to what you could split on the colon and then reference each.
this_time = this_time.split(':') # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]
Edit 2:
To put it all back together then:
from datetime import date, datetime, time, timedelta
this_time = '7:00'
this_time = this_time.split(':') # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])
dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()
If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.

Django filter bunch of latest entries in models

My problem is I'm save all entries in django model but now I want filter these all entries on my view.
I'm trying
delBoySale.objects.latest('timeStamp')
It return only single entry but I want all entries that are save last.
What I do?
Use the slice syntax to get a number of objects:
delBoySale.objects.all().order_by('-timeStamp')[:10]
This will return ten last saved instances.
To get the instances created in the last hour use filter by timeStamp field:
from datetime import timedelta
from django.utils.timezone import now
hour_ago = now() - timedelta(hours=1)
delBoySale.objects.filter(timeStamp__gt=hour_ago).order_by('-timeStamp')
You should use 'gte' expression:
https://docs.djangoproject.com/en/1.7/ref/models/querysets/#gte
if 'timeStamp' is DateTimeField:
last_date = datetime.datetime.now() - datetime.timedelta(hours=4)
if 'timeStamp' is IntegerField:
last_date = datetime.datetime.now() - datetime.timedelta(hours=4)
last_date = int(last_date.strftime("%s"))
and filter:
delBoySale.objects.filter(timeStamp__gte=last_date)

Categories