【问题标题】:How filter by date and convert datetime如何按日期过滤并转换日期时间
【发布时间】:2021-10-09 22:31:59
【问题描述】:

我正在从前面发送一些用 vue 制作的日期。我在 django 的 viewSet 中收到这些日期,我想从这些收到的日期中过滤数据。 我有两个问题:

  1. 如何将日期转换为 Python 日期时间?

  2. 如何过滤等于或大于或等于或小于的日期。 =>

前面的日期格式:2021-08-03 10:12:14

日期格式在后面:

    # print(type(fechas['desde']))
    fecha <class 'str'>
    # print(fechas['desde'])
    fecha 2021-08-03 10:12:14

视图集:

            class TecnicosViewSet(
                    mixins.CreateModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.RetrieveModelMixin,
                    mixins.ListModelMixin,
                    mixins.DestroyModelMixin,
                    viewsets.GenericViewSet):

                queryset = Tecnico.objects.all()
                serializer_class = Tecnicoserializer

                def list(self, request):
                    dataQ = request.GET
                    newQ = json.dumps(dict(dataQ))
                    newQ1= json.loads(newQ)
                    tecnicos = ''
                    fechas= json.loads(newQ1['fechas'][0])
                    for item in newQ1['tecnicos']:
                        itemN = json.loads(item)
                        tecnicos = itemN['tecnicos']
                    print('fechas', fechas['desde'], fechas['hasta'])
                    # fecha = datetime.strptime(fechas['desde'], '%Y-%m-%d %H:%M')
                    print('fecha', type(fechas['desde']))
                    print('fecha', fechas['desde'])
                    for id in tecnicos:
                        ordenes = Servicio_realizados_orden_trabajo.objects.filter(date_range = [fechas['desde'], fechas['hasta']]).filter(state = 1).filter(tecnico = id)
                        ordenS = ServicioRealizadosserializer(ordenes, many=True)


                    return Response({'OK'})

正如我之前修复的那样:我想将该日期转换为可理解的 Python 格式,然后使用转换后的日期按该日期过滤数据。

在 viewewt 中看到的 for 循环是我尝试进行查询的地方。

【问题讨论】:

    标签: python django database datetime django-rest-framework


    【解决方案1】:

    根据您的代码,我认为您非常接近...

    您基本上使用 strptime 将字符串转换为所需格式的日期,然后在创建 python 日期时间对象后进行比较。

    这是一个例子:

    from datetime import datetime
    
    date = datetime.strptime("2021-08-03 10:12:14", "%Y-%m-%d %H:%M:%S")
    if date >= datetime.strptime("2021", "%Y"):
        print('After or in 2021')
    if date >= datetime.strptime("2021-09", "%Y-%m"):
        print('After or in September 2021')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 2013-10-20
      • 2018-01-25
      • 2022-07-16
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2021-09-01
      相关资源
      最近更新 更多