Trying to pass a datetime object via pymongo, as I can't use a hardcoded "datetime" as shown in all the pymongo documentation (eg: "2015-12-24T11:59:00Z").
Simply want to delete collections over 7 days old. Why is it erroring on "an integer is required" when I'm passing it a UTC date via 'newDate'?
from datetime import datetime, timedelta
from pymongo import MongoClient
newDate = datetime.utcnow() - timedelta(days=7)
result = db.collection.remove({"receivedDateUtc" : { '$lte' : datetime(newDate) }} )
The reason is that newDate is already a datetime object.
result = db.collection.remove({'receivedDateUtc' : { '$lte' : newDate }} )
Demo:
In [67]: newDate = datetime.utcnow() - timedelta(days=7)
In [68]: newDate
Out[68]: datetime.datetime(2015, 12, 29, 22, 2, 41, 391369)
Related
I do have a model as below
class Employee(models.Model):
employee_name = models.CharField(max_length=100)
joining_Date = models.DateField(blank=False, null=False)
I want to get data for last six months (including current month) joined employee count month wise.
Example:
July : 12,
June : 10,
May : 8,
April : 16,
March : 13,
February : 10,
joining_Date stores data like "2022-07-22". How to get done this by having date field?
To get the count of new employees per month you will need to annotate and use Trunc to just get the month, see below:
from datetime import date
from dateutil.relativedelta import relativedelta
from django.db.models.functions import Trunc
six_months_ago = date.today() + relativedelta(months=-6)
employees_per_month = Employee.objects.filter(join_date__gte=six_months_ago)\
.annotate(
joining_month=Trunc('joining_date', 'month', output_field=DateField())
) \
.order_by('joining_month') \
.values('joining_month') \
.annotate(employees=Count('joining_month'))
This will give you a queryset with the following structure:
<QuerySet [{'joining_month': datetime.date(2022, 6, 1), 'employees': 2},
{'joining_month': datetime.date(2022, 7, 1), 'employees': 1}, ...
Edit
To convert the QS into a flat dict:
employee_count_dict = {}
for employee_count in employees_per_month:
employee_count_dict[val['joining_month']] = val['employees']
You can try to find maximum apropriate date, and filter by it
from datetime import date
from dateutil.relativedelta import relativedelta
def find_employee(request):
today = date.today()
six_months = today - relativedelta(months=6)
emloyed_for_six_month = Employee.objects.filter(joining_Date__gte = six_months)
Your employee model should be named with a capital letter. It is conventional
https://stackoverflow.com/a/386054/14632651
I am using Django and have a problem with a date that I need to calculate.
The Variable data > test should be 17:00 and not 15:00. Why does this happen as soon as I format the date?
My timezone is Europe/Berlin. Changing the timezone has to effect to the time printing in test. It is always -2h
def date(req):
now = timezone.now()
model = MyModel.objects.filter(date__gt=now).first()
next = model.date
future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
open = next-future
date = next.strftime('%Y/%m/%d')
data = {
'next': next,
'date': date,
'time': open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f'),
'test': open.strftime('%Y/%m/%d %H:%M:%S%z')
}
What I get:
next: 20. November 2021 18:30
date: 2021/11/20
time: 2021-11-20 15:15:00.000000
test: 2021/11/20 15:00:00+0000
https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#naive-and-aware-datetime-objects
You should use:
from django.utils import timezone
now = timezone.now()
Datetime isn't time-zone aware.
You cut the timezone info (the offset +02:00) with .strftime(). You need to include it with %z.
In case you want to convert it to a time string with the offset already added.
open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
This works for me.
from django.utils import timezone
def date(req):
now = timezone.now()
model = MyModel.objects.filter(date__gt=now).first()
next = model.date
future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
open = next-future
date = timezone.localtime(open)
data = {
'next': date.strftime('%Y/%m/%d %H:%M:%S'),
'date': date.strftime('%Y/%m/%d'),
'time': date.strftime('%H:%M:%S'),
}
In my project I have object with datetime field
startdate = models.DateTimeField(default="1999-01-01 00:00:00")
I need create new object and send datetime = "2015-12-9"
calen = models.calendar()
calen.startdate = datetime.strptime(request.POST["date"], "%Y-%m-%d")
calen.save()
In this object I see
calen.startdate => datetime.datetime(2015, 12, 9, 0, 0)
all right.
in pqAdmin3, postgres DB this field = "2015-12-09 08:00:00+02"
wrong 8 hours!!!! ->6+2
When I select this object calen.startdate
datetime.datetime(2015, 12, 9, 6, 0, tzinfo=<UTC>)
extra 6:00!!!!
I tried to make a complete date, now(),but all the same is extra 6 hours
Do not use django.utils.datetime for database fields. Use timezone instead.
from django.utils import timezone
now = timezone.now()
I tried to declared a variable contains of Datetime like this
ts1.departure_date = '2012-03-03 10:10:10'
but then I got this error
StatementError: (exceptions.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
I wonder what is the correct way to declare a variable with datetime format? Thanks in advance
First import the datetime class:
from datetime import datetime
Then create a datetime object and use that to set your attribute:
ts1.departure_date = datetime(2012, 3, 3, 10, 10, 10)
expiration_year = int(form.expiration_date.data[:4])
expiration_month = int(form.expiration_date.data[5:7])
expiration_date = int(form.expiration_date.data[8:10])
expiration_date =datetime(expiration_year,expiration_month,expiration_date)
Ultra strange error that encountered with SQLAlchemy with both SQLite and Postgres
from datetime import datetime
....
#WORKS
lending_operation = models.LendingOperation(
device_id = device.device_id,
start_using = datetime.now()
)
db.session.add(lending_operation)
db.session.commit()
#DIDN'T WORK
lending_operation = models.LendingOperation(
currency = "USD",
device_id = device.device_id,
start_using = datetime.now()
)
db.session.add(lending_operation)
db.session.commit()
#MODEL: models.py
class LendingOperation(db.Model):
.....
start_using = db.Column(db.DateTime, default=datetime.now )
.....
currency = db.Column(db.DateTime)
Hope it helps, didn't find any info on the exception
Hi I'm having trouble storing a datetime object in a dictionary in python. When I try to retrieve the datetime object to compare with another datetime object the returned object is a str not a datetime.
class Course(models.Model):
StartDate = models.DateTimeField()
dict = {}
myDate = Course.StartDate
dict['date'] = myDate
today = datetime.datetime.today()
if today > dict['date']:
pass
assume Course.StartDate returns a datetime object.
It does look you're missing something in your code here, because what you're trying to do works just fine.
With this model:
class Course(models.Model):
# auto_now_add for convenience when testing
start_date = models.DateTimeField(auto_now_add=True)
I created an object:
>>> c = Course.objects.create()
And created a dictionary:
>>> mydict = {}
Assigned the start_date attribute to a dictionary key:
>>> mydict['date'] = c.start_date
Access the value as a datetime object:
>>> mydict['date']
datetime.datetime(2012, 3, 1, 16, 55, 49, 723208)
And can compare the dictionary value to a datetime object:
>>> datetime.datetime.today() > mydict['date']
True