2014-01-25 27 views
0

我想從datetime字段中減去一個整數值。這裏date_joined是一個datetime字段,年齡是一個整數字段。從datetime字段減法整數值

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() 

回答

1

用途:

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

從減去age年0。

請注意,這是一個很好的快速解決方案,但不是非常強大。請看下面的輸出:

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

正如你所看到的,因爲閏年​​(年,實際上有366天)的,其結果是,我們其實是想在日後4天。更可靠的解決方案是:

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

如果您在生產中使用此功能,請參閱更新的答案! – sundance