Thameem
Thameem

Reputation: 3636

substract integer value from datetime field

I want to subtract an integer value from a datetime field. Here date_joined is a datetime field and age is an integer field.

views.py

def index(request):  
    profiles = profiles.objects.all()
    for profile in profiles: 
        age = person.age
        date_joined = person.date_joined
        date_of_birth = date_joined - age
        p = date_of_birth(date_of_birth = date_of_birth,activated = 1)
        p.save()

models.py

class profiles(models.Model):
    date_joined =  models.DateTimeField (max_length=1)
    age = models.IntegerField()

Upvotes: 0

Views: 91

Answers (1)

sundance
sundance

Reputation: 2945

Use:

date_joined - (datetime.timedelta(365) * age)

To subtract age years from date_joined.

Just a note that this is a good quick-and-dirty solution, but is not very robust. Consider the following output:

>>> datetime.datetime(2013, 12, 12) - datetime.timedelta(365) * 15
datetime.datetime(1998, 12, 16, 0, 0)

As you can see, because of leap years (years that actually have 366 days), the result is 4 days after the date we actually wanted. A more robust solution would be:

date_joined.replace(year = date_joined.year - age)

Upvotes: 1

Related Questions