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)