conversion of datetime Field to string in django queryset.values_list()

后端 未结 8 1827
南方客
南方客 2020-12-06 09:29

I have a queryset like:

qs = MyModel.objects.filter(name=\'me\').values_list(\'activation_date\')

here activation_date is

相关标签:
8条回答
  • 2020-12-06 09:37

    I did it this way

    .annotate(date_str=ExpressionWrapper(
                Func(F('date'), Value('%d/%m/%Y %H:%i'), function='DATE_FORMAT'), output_field=CharField()
            ))
    
    0 讨论(0)
  • 2020-12-06 09:41

    https://docs.djangoproject.com/en/2.2/ref/models/fields/#datetimefield

    A date and time, represented in Python by a datetime.datetime instance.

    You can get a string representation of a DateTimeField casting it directly:

    str(obj)
    # obj = qs[0][0] ? or qs[0][1] ?
    

    You'll get result like this (in this example I use datetime.datetime.now() since a DateTimeField is represented by datetime.datetime is the same behavior):

    >>> now = datetime.datetime.now()
    >>> str(now)
    '2013-06-26 00:14:26.260524'
    

    if you want less information or formatted in other mode you can use strftime() function for format them. see:

    >>> now.strftime('%Y-%m-%d %H:%M')
    '2013-06-26 00:14'
    
    0 讨论(0)
  • 2020-12-06 09:41

    If you are using Postgres, you can do it like this (date format options here). The solution is database dependent, but it sure beats looping though a long list in Python land after your perform the query.

    qs = MyModel.objects.filter(name='me')
    qs = qs.extra(select={'datestr':"to_char(activation_date, 'YYYY-MM-DD HH24:MI:SS')"})
    qs = qs.values_list('datestr')
    

    I am sure MySQL has some equivalent function as Postgres's to_char, but you'll have to find that on your own as I am not a MySQL guy.

    0 讨论(0)
  • 2020-12-06 09:44
    qs = MyModel.objects.filter(name='me')
    qs = qs.extra(select={'datestr':"DATE_FORMAT(activation_date, '%Y-%m-%d')"})
    qs = qs.values_list('datestr')
    
    0 讨论(0)
  • 2020-12-06 09:48

    You can also convert the date in queryset to string using map function. Example:

    qs = MyModel.objects.filter(name='me').values_list('activation_date', flat=True)
    data = map(str, qs)
    
    0 讨论(0)
  • 2020-12-06 09:54

    extra() is an old API that Django aims to deprecate at some point in the future. I would avoid using it.

    Try the following instead:

    from django.db.models import F, Func, Value, CharField
    
    qs.annotate(
      formatted_date=Func(
        F('date'),
        Value('dd.MM.yyyy hh:mm'),
        function='to_char',
        output_field=CharField()
      )
    )
    

    This works only with a database that supports the to_char date type formatting function. Postgres provides this function by default. If you use a MSSQL backend you could swap to_char with FORMAT. For Oracle consult their documentation, etc.

    After the queryset is evaluated this will add the annotation formatted_date to each object in the queryset that is returned.

    0 讨论(0)
提交回复
热议问题