Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从datetime字段中减去整数值_Python_Django_Python 2.7 - Fatal编程技术网

Python 从datetime字段中减去整数值

Python 从datetime字段中减去整数值,python,django,python-2.7,Python,Django,Python 2.7,我想从datetime字段中减去一个整数值。这里的date是一个datetime字段,age是一个整数字段 视图.py def index(request): profiles = profiles.objects.all() for profile in profiles: age = person.age date_joined = person.date_joined date_of_birth = date_joine

我想从
datetime
字段中减去一个整数值。这里的
date
是一个
datetime
字段,age是一个整数字段

视图.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()
class profiles(models.Model):
    date_joined =  models.DateTimeField (max_length=1)
    age = models.IntegerField()
型号.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()
class profiles(models.Model):
    date_joined =  models.DateTimeField (max_length=1)
    age = models.IntegerField()
使用:

从加入日期中减去年龄

需要注意的是,这是一个很好的快速而肮脏的解决方案,但不是很健壮。考虑以下输出:

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