Reputation: 542
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.
Upvotes: 0
Views: 2582
Reputation: 44
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
Upvotes: 0
Reputation: 317
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)
Upvotes: 0
Reputation: 569
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)
Upvotes: 1