Django: Get Months since a certain datetime - python

I'm trying to get the number of months since a model is created.
My Model looks like this:
class Plan(models.Model):
title = models.CharField(max_length=50)
date_created = models.DateTimeField(default=timezone.now)
plan_type = models.IntegerField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
Now i want to make a method that returns the number of months since the date_created.
Tanks for any help :D

Comparing dates creates a datetime.timedelta object that you can use to get the difference between dates.
from datetime import timedelta
from django.utils.timezone import now
delta: timedelta = now() - plan.date_created
delta.days # Number of days between dates.
You can then use that value to convert it to months or years.
The other alternative would be a bit more complicated, but since DateTimeField returns a datetime.datetime object, you can also access the month number of the original date and compare it against todays date.
e.g.
from django.utils.timezone import now
month_diff = now().month - plan.date_created.month
The problem with the second alternative is that you then have to take into account if they are the same year or not, and if they are not you then have to take that into account when you get the month difference.

You can write a property in your model like
from django.utils import timezone
class Plan(models.Model):
title = models.CharField(max_length=50)
...
#property
def get_month(self):
return self.date_created.month - timezone.now().month
Then you can get the value like this
>>> Plan.objects.first().get_month
4

Related

Extracting month from date in flaskform with different format

I am trying to create a code made out of months and count number. The count number is easy, but I don't understand how to extract month from date form.
Model:
req_date =db.Column(db.Date, nullable=False, default=date.today())
req_code =db.Column(db.String, nullable=False, unique=True)
Form:
reqdate = DateField('Request Date')
Route:
currentyear = extract('year',form.reqdate.data)
currentmonth= extract('month', form.reqdate.data)
ronum = 'RO-'+'/'+str(currentmonth)+'/'+str(currentyear)
I tried using this function for my route I found before, but it doesn't seem to work.
What I got instead of like RO-/01/2021. I got this error:
RO-/EXTRACT(month FROM :param_1)/EXTRACT(year FROM :param_1)
Does anyone know the function to extract it? Or if the function isn't wrong, where did I go wrong?
DateField returns a datetime.date object
That means you should be able to do:
# Data from the form which has been formatted to datetime.date object
current_date = form.reqdate.data
current_year = current_date.year
current_month = current_date.month
Attributes available on datetime.date can be found here

How to filter date According to Today Current Date in Django?

I am trying to filter date in Django according to current date, But it's displaying mr 0 results, Please let me know Where I am mistaking.
Hers is my models.py file...
class Customer(models.Model):
name = models.CharField(null=True, blannk=True)
customer_date = models.DateTimeField(null=True, blannk=True)
here is my views.py file, where i am trying to get date according to today date...
from datetime import datetime, timedelta, time, date
def getdate(request):
today=datetime.today()
customer_data = Customer.objects.filter(customer_date=today).count()
print(customer_data, "Count Values")
I see some issue in your date filter. When you do:
datetime.datetime.today()
#2020-11-04 10:57:22.214606
this give complete timestamp.
However you want to do date match only.so, try something like code.
today = datetime.today().date()
#today=datetime.today()
customer_data = Customer.objects.filter(customer_date__date=today).count()
hope this may help your query.
I saw you mistyped blank as blannk

DurationField or Timedelta

im having a problem trying to set a duration in my to-do tasks.
i've tried with DurationField and some people told me to try the timedelta in your forms.py but im not quite shure how to pass the difference like (6days) from my two model DateField (start and end).
Models.py
from django.db import models
from datetime import datetime, timedelta
class To_do (models.Model):
task = models.CharField(max_length=150)
topic = models.CharField(max_length=150)
how = models.TextField(max_length=600)
start = models.DateField(default=datetime.today)
end = models.DateField(blank=False)
duration = models.DurationField(default=timedelta)
i'd like to display the difference for the user and after set an alarm for less than 3 days etc.
How do I solve this?
The difference between two date or date/time values is a timedelta.
delta_time = end - start
Or if you need to code a delta-time constant from other numbers
from datetime import timedelta
my_delta = timedelta( days=3, hours=12, minutes=1 ) # half a week plus a minute
Don't use timedelta as the name as the default value if you are importing it! If what you mean to do is to pass a callable to calculate a timedelta, define a function to do that as above, and pass it as the default value.

Find objects with date and time less then 24 hours from now

I have model with two fields:
class Event(models.Model):
date = models.DateField(_(u'Date'))
time = models.TimeField(_(u'Time'))
I need to find all objects where date&time is in 24 hours from now.
I am able to do this when using DateTime field, but I am not sure how to achieve this when fields are separated. Thanks in advance.
For the simple case (not sure if all are simple cases though...), this should do the trick:
import datetime
today = datetime.datetime.now()
tomorrow = today + datetime.timedelta(days=1)
qs_today = queryset.filter(
date=today.date(),
time__gte=today.time(),
)
qs_tomorrow = queryset.filter(
date=tomorrow.date(),
time__lt=tomorrow.time(),
)
qs = qs_today | qs_tomorrow
As you state you can do what you want with a DateTimeField, but now with the separate fields, I understand your issue is how to combine them.
Looking at the docs for DateField - your date variable is a datetime.date instance and similarly for TimeField time is a datetime.time. You can convert these into a datetime.datetime by using combine()
import datetime as dt
datetime = dt.datetime.combine(date,time)
You now have the datetime object as you would have from DateTimeField. You say in the question you can do the 24 hour from now bit from there, although let me know in comments if you need that made explicit.
Caveat I combine will fail where one of the fields is None - you state this can't happen, so I haven't added any error checking or validation of this.
EDIT
It occurs to me that the problem may not be the combination, but adding the calculated field to the Event object. You could look at this Q&A, or this. In summary you define the calculated value in a function in your class and then make it a property - either with a decorator or a function call. There's an example in the docs, adapting for your case:
def _get_datetime(self):
'''Returns a combination of date and time as a datetime'''
return dt.datetime.combine(self.date,self.time)
datetime = property(_get_datetime)
This should behave in the same way as you would expect a DateTimeField to behave.
You can use Q objects to search for "yesterday after current time or today before current time":
from django.db.models import Q
from .models import Event
from datetime import datetime, timedelta
def get_event_during_last_day():
now = datetime.now()
today = now.date()
yesterday = (now - timedelta(day=1)).date()
time = now.time()
query_yesterday = Q(date=yesterday, time__gt=time)
query_today = Q(date=today, time__lt=time)
return Event.objects.filter(query_yesterday | query_today)

Django: How to get a time difference from the time post?

Say I have a class in model
class Post(models.Model):
time_posted = models.DateTimeField(auto_now_add=True, blank=True)
def get_time_diff(self):
timediff = timediff = datetime.datetime.now() - self.time_posted
print timediff # this line is never executed
return timediff
I defined a get_time_diff to get the time difference from the time when the Post is posted up to now, according to the document, the DateTimeField should be able to be converted to datetime automatically, is that correct? Why the print statement is never being run? How can you extract the time difference?
Beside, if you get a time difference, is there an easy way to convert the time difference to an integer, like the number of seconds of the total time.
Your code is already working; a datetime.timedelta object is returned.
To get the total number of seconds instead, you need to call the .total_seconds() method on the resulting timedelta:
from django.utils.timezone import utc
def get_time_diff(self):
if self.time_posted:
now = datetime.datetime.utcnow().replace(tzinfo=utc)
timediff = now - self.time_posted
return timediff.total_seconds()
.total_seconds() returns a float value, including microseconds.
Note that you need to use a timezone aware datetime object, since the Django DateTimeField handles timezone aware datetime objects as well. See Django Timezones documentation.
Demonstration of .total_seconds() (with naive datetime objects, but the principles are the same):
>>> import datetime
>>> time_posted = datetime.datetime(2013, 3, 31, 12, 55, 10)
>>> timediff = datetime.datetime.now() - time_posted
>>> timediff.total_seconds()
1304529.299168
Because both objects are timezone aware (have a .tzinfo attribute that is not None), calculations between them take care of timezones and subtracting one from the other will do the right thing when it comes to taking into account the timezones of either object.
Assuming you are doing this within a template, you can also use the timesince template tag.
For example:
{{ blog_date|timesince:comment_date }}
Your code
timediff = datetime.datetime.now() - self.pub_date
should work to get the time difference. However, this returns timedelta object. To get difference in seconds you use .seconds attribute
timediff = datetime.datetime.now() - self.pub_date
timediff.seconds # difference in seconds.
Just in case you want to put this process in you Django signals. Here's the one that is working for me. Hope this helps!
from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import YourModel
from datetime import datetime
#receiver(pre_save, sender = YourModel)
def beforeSave(sender, instance, **kwargs):
date_format = "%H:%M:%S"
# Getting the instances in your model.
time_start = str(instance.time_start)
time_end = str(instance.time_end)
# Now to get the time difference.
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
Simply we can add the custom property to calculate the time difference with the help #property decorator in that model.
from django.utils import timezone
class Post(models.Model):
time_posted = models.DateTimeField(auto_now_add=True, blank=True)
content = models.TextField()
#property
def time_diff(self):
return timezone.now() - self.time_posted
time_diff will return object of datetime.timedelta
post = Post.objects.get(pk=1) # Post model object
# time diff in seconds.
post.time_diff.seconds
>>> 652
# time diff in days.
post.time_diff.days
>>> 0
Already answered above nicely by Martijn Pieters, just adding #property, and django.utils.timezone to calculate the difference with respective timezone from settings.py

Categories

Resources