1. 程式人生 > >計算時間

計算時間

from django.utils import timezone
from dateutil import relativedelta
class DeviceOfPowerSerializer(serializers.ModelSerializer):
    """
    用於能源裝置列表的serializer
    """
    electric_num_for_now = serializers.SerializerMethodField(read_only=True, help_text='當前電量')
    electric_num_for_day = serializers.SerializerMethodField(read_only=True, help_text='當天用電量')
    # electric_num_for_week = serializers.SerializerMethodField(read_only=True, help_text='本週用電量')
    electric_num_for_month = serializers.SerializerMethodField(read_only=True, help_text='本月用電量')

    def get_electric_num_for_now(self, obj):
        result = ElectricNum.objects.filter(device=obj)
        if result:
            result = result.last()
            return result.num
        return 0

    def get_electric_num_for_day(self, obj):
        now = timezone.now()
        yesterday = now - timezone.timedelta(days=1)

        result_today = ElectricNum.objects.filter(device=obj, create_time__date=now.date())
        result_yesterday = ElectricNum.objects.filter(device=obj, create_time__date=yesterday.date())

        today_num = result_today.last().num if result_today else 0
        yesterday_num = result_yesterday.last().num if result_yesterday else 0

        return today_num - yesterday_num

    def get_electric_num_for_month(self, obj):
        now_time = timezone.now()
        pass_time = now_time - relativedelta.relativedelta(months=-1)

        result_now = ElectricNum.objects.filter(device=obj,
                                                create_time__year=now_time.year,
                                                create_time__month=now_time.month)
        result_pass = ElectricNum.objects.filter(device=obj,
                                                 create_time__year=pass_time.year,
                                                 create_time__month=pass_time.month)

        now_num = result_now.last().num if result_now else 0
        pass_num = result_pass.last().num if result_pass else 0

        return pass_num - now_num

    class Meta:
        model = Device
        fields = ('id', 'name', 'electric_num_for_now', 'electric_num_for_day', 'electric_num_for_month', 'create_time')