Ad

How To Add An Integer To Current Month And Then Update Datefield In Django

- 1 answer

I am just trying to get the current month and then add an integer to it for example 3 months, then update my datefield obj to that value.

my view.py :

def worklist(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    vessel = Vessel.objects.all()
    component = vessel_id.components.all()
    components = component.prefetch_related(
        'jobs').filter(jobs__isnull=False)
    if request.method == 'POST' and 'form-execute' in request.POST:
        this_job = Job.objects.get(pk=request.POST.get('execute_job_id'))
        job_type = this_job.type
        job_due_date=this_job.due_date
        job_interval =this_job.interval
        dt = datetime.datetime.today().month
        if job_type =='O':
            this_job.delete()
        else: job_due_date = dt + relativedelta(months=job_interval)
        return HttpResponseRedirect(request.path_info)
    context = {"component": components,"vessel_id":vessel_id,"vessel":vessel }
        
    return render(request, "worklist.html", context)

i just want say thisjob due date equal to this month plus this job interval which is an integer

here is model.py if it helps :

class Job(models.Model):
    job_type = (
        ('I', 'Interval'),
        ('O', 'One time'),
    )
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    type = models.CharField(max_length=1, choices=job_type)
    interval = models.IntegerField()
    is_critical = models.BooleanField()
    due_date = models.DateField()
    rank = models.ManyToManyField(UserRank,related_name='jRank')
    component = models.ForeignKey(
        Component, related_name='jobs', on_delete=models.CASCADE)
    runninghours = models.ForeignKey(
        RunningHours, related_name="RHjobs", on_delete=models.CASCADE,blank=True)   

    def __str__(self):
        return self.name
Ad

Answer

It's datetime.datetime.now() (or datetime.date.today())

If you want to skip forward an amount of time equal to N 30-day "months"

now = datetime.datetime.now() + datetime.timedelta ( seconds=N*30*24*60*60 )

If you want to re-set the month it's much harder because of issues with things like leap-years, and the varying number of days in a month.

year = now.year
month = now.month
day = now.day
hour = now.hour
minn = now.minute
sec = now.second

month = month + N  

# some issues ... month > 12? day = 31 and month = 11?
# after you resolve them

future_time = datetime.datetime( year, month, day, hour, minn, sec)

(min is a Python built-in. You can overlay it, but it's not good practice. Hence, minn)

Ad
source: stackoverflow.com
Ad