How To Calculate days Between Two Dates In Django
我想计算两个在姜哥的日期的时差。我正在尝试此代码:
我的模型:
1 2 | dateDeDebut = models.DateTimeField(auto_now_add=False, auto_now=False) dateDeFin = models.DateTimeField(auto_now_add=False, auto_now=False) |
我的类视图集:
1 2 3 4 5 6 7 8 | class MyClassViewSet(viewsets.ModelViewSet): serializer_class = MyClassSerializer permission_classes = (IsAuthenticated, ) def perform_create(self, serializer): if (condition): diff = (self.request.data.get('dateDeFin') - self.request.data.get('dateDeDebut')).days #never executed print(diff) |
我得到这个错误:
1 | unsupported operand type(s) for -: 'unicode' and 'unicode' |
这个解决方案对我有效
1 2 3 4 5 6 7 8 9 10 | class MyClassViewSet(viewsets.ModelViewSet): serializer_class = MyClassSerializer permission_classes = (IsAuthenticated, ) def perform_create(self, serializer): if (condition): start_date = datetime.datetime.strptime(self.request.data.get('dateDeFin'),"%Y-%m-%d %H:%M") end_date = datetime.datetime.strptime(self.request.data.get('dateDeDebut'),"%Y-%m-%d %H:%M") diff = abs((end_date-start_date).days) print(diff) |