Django / Python - Extract Date from DateTimeField - python

Take the example model as follows:
import datetime
class Calendar(models.Model)
def now():
return datetime.date.today()
def 24hrslater():
return datetime.date.today() + datetime.timedelta(days=1)
now = models.DateTimeField(default=now)
24hrslater = models.DateTimeField(default=24hrslater)
Is there a way to extract just the date from these date time fields? I have tried the following (as suggested on another thread):
todaysdate = now.date()
But had no success with it. The error that comes up on the command line when running "python manage.py check" is:
AttributeError: 'DateTimeField' object has no attribute 'date'
Is there a way to do this?

def now():
return datetime.today().date()
this will return the current date
Calendar.objects.filter(datetimefield__date='your_date')

I'm not sure that I understand your question correctly, but you can get the date from DateTimeFields like this.
from django.db import models
from django.utils import timezone
class Calendar(models.Model):
now = models.DateTimeField(default=timezone.now)
twenty_four_hours_later = models.DateTimeField(
default=lambda: timezone.now() + timezone.timedelta(hours=24))
c = Calendar()
print(c.now.date())
print(c.twenty_four_hours_later.date())

Related

add time when we save a Timefield in django

I have a dateTime field in a model. The dateTime field named breakfast_start_time takes an input.
I have to save another variable or timefield(whichever is better) named breakfast_attendence_start_time whose value should be automatically saved 15 minutes less than the breakfast_start_time.
For this we use
def save(self, *args, **kwargs):
#do something
super().save(*args, *kwargs)
I am trying to do
breakfast_attendence_start_time = breakfast_start_time - time(15,0)
but it is giving error that
class TimeField does not define '_sub_', so the '-' operator cannot be used on its instances
Edited:
Here is the full code
class Hostel(models.Model):
name = models.CharField(max_length=15)
breakfast_start_time = models.TimeField()
lunch_start_time = models.TimeField()
snacks_start_time = models.TimeField()
dinner_start_time = models.TimeField()
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
I am taking start time from admin panel and I want to add 4 more variable/field like breakfast_attendence_start_time whose value should be saved automatically 15 minutes earlier than breakfast_start_time how can I achive that.
You should use timedelta to sub specific time with DateTime field. Such as
import datetime
time_before_15_minute = datetime.datetime.now() - datetime.timedelta(minutes=15)
Use DateTimeField instead of TimeField and use timedelta to make substractions
from datetime import datetime, timedelta
n = datetime(2019, 10, 4, 12, 30)
m = n - timedelta(minutes = 15) # m is now datetime(2019, 10, 4, 12, 15)
You can play with the DateTimeField but this will return time of when this function was called or used. Hope it helps
from django.utils import timezone
class AKA(models.Model):
create_time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.create_time

comparing the datefield to today and changing the integerfield automatically every day

I'm making a website using django.
class Member(models.Model):
...
end_date = models.DateField(blank=True, default=(datetime.now() + timedelta(days=30)))
Membership_status = models.IntegerField(blank=True, null=True, default=1) # 1 = active, 0=deactivate, 2=refund
What I want to do is comparing the end_date field to today.date every 1.a.m. and if today's day < end_date, Membership_status field is changed to 0 automatically.
I heard I should use django-kronos(https://github.com/jgorset/django-kronos).
But I can't understand the using method.
Is there anyone can tell me details how I implement what I want?
Any help will be very helpful to me, thanks!
First of all, this is not an answer to your original query, but merely a suggestion for your future,
Never pass a function call into your field defaults. If you did, the function would be evaluated at the time of your migrations. If you look into the migration files you can see for sure. Instead wrap it in a function and pass that as a callable.
Eg:
from django.utils import timezone
def TODAY():
return timezone.now().date()
def NEXT_MONTH_DAY():
return TODAY() + timedelta(days=30)
Now, in your models,
class Member(models.Model):
...
end_date = models.DateField(blank=True, default=NEXT_MONTH_DAY)
This way the function NEXT_MONTH_DAY is called whenever an instance of Member is created.
EDIT:
For your original query, I haven't tested the code, but I suppose you are looking for maybe something like this,
import kronos
#kronos.register('0 1 * * *')
def the_task():
for member in Member.objects.all():
if TODAY() == member.end_date:
member.Membership_status = 0
member.save()

Error - "SQLite DateTime type only accepts Python " "datetime and date objects as input."

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

Can't save datetime.now() to DateTimeField

I've defined a model as follows (Shortened it for the question)
from datetime import datetime, date, timedelta
class Case(models.Model):
received_email_sent = models.DateTimeField(null=True, blank=True, default=None)
def send_received_email(self):
message = settings.EMAIL_HEADER + self.case_received_email() + settings.EMAIL_FOOTER
send_mail('Subject here', message, settings.EMAIL_HOST_USER, ['xxx#xxx.com'], fail_silently=False)
self.received_email_sent = datetime.now()
and in the view I call send_received_email on an existing object. I know that the send_received_email block is being entered because I'm receiving the emails every time I test this out, but the self.received_email_sent = datetime.now() part is leaving that field as its default value (None) every time. Here's the relevant part of the view:
from logbook.models import Case
def job_email(request, case_id):
case = get_object_or_404(Case,pk=case_id)
case.send_received_email()
return HttpResponseRedirect('/jobs/'+str(case.case_id))
I have also tried an alternative method, where saving the field is done in the view instead of the model, like so:
models:
class Case(models.Model):
received_email_sent = models.DateTimeField(null=True, blank=True, default=None)
def send_received_email(self):
message = settings.EMAIL_HEADER + self.case_received_email() + settings.EMAIL_FOOTER
send_mail('Subject here', message, settings.EMAIL_HOST_USER, ['xxx#xxx.com'], fail_silently=False)
#self.received_email_sent = datetime.now()
views:
from datetime import datetime
from logbook.models import Case
def job_email(request, case_id):
case = get_object_or_404(Case,pk=case_id)
case.send_received_email()
case.received_email_sent = datetime.now()
return HttpResponseRedirect('/jobs/'+str(case.case_id))
I have also tried both of the above routes with various tweaks like removing the brackets on now() and changing from datetime import datetime to just import datetime. No joy. Thanks for having a look at this.
You need to call self.save() at the end of send_received_email().

python - django: why am I getting this error: AttributeError: 'method_descriptor' object has no attribute 'today'?

I have the following python code:
from django.db import models
from datetime import datetime
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
In a python shell, I am trying to run:
p = Poll.objects.get(pk=1)
p.was_published_today()
The first line works fine but the second line gives me this error:
AttributeError: 'method_descriptor' object has no attribute 'today'
You probably want "import datetime", not "from datetime import datetime".
"date" is a class on the datetime module, but it is also a method on the "datetime.datetime" class.
The top answer is correct, but if you don't want to import all of datetime you can write
from datetime import date
and then replace
datetime.date.today()
with
date.today()
You need do like this one (ipython output)
In [9]: datetime.today().date()
Out[9]: datetime.date(2011, 2, 5)
So need to be
def was_published_today(self):
return self.pub_date.date() == datetime.today().date()

Categories

Resources