Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a queryset like:

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

here activation_date is DateTimeField in models. When I download excel sheet from this qs I am not getting activation date in string format. How can I convert this field('activation_date') in string or how to typecast it in qs?

like image 939
Navera Avatar asked Jun 13 '13 11:06

Navera


Video Answer


2 Answers

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' 
like image 162
Victor Aurélio Avatar answered Oct 11 '22 13:10

Victor Aurélio


extra is deprecated in Django 2.0

That's why I think the best solution to get a stringified datetime is:

foo_bar = FooBarModel.objects.annotate(     str_datetime=Cast(         TruncSecond('some_datetime_field', DateTimeField()), CharField()     ) ).values('str_datetime').first() 

The result is:

foo_bar.str_datetime: (str)'2014-03-28 15:36:55' 

Also I'd like to mention that you can format it as well in any way you want like:

from django.db.models import Value  foo_bar = FooBarModel.objects.annotate(     day=Cast(ExtractDay('some_datetime_field'), CharField()),     hour=Cast(ExtractHour('some_datetime_field'), CharField()),     str_datetime=Concat(         Value('Days: '), 'day', Value(' Hours: '), 'hour',          output_field=CharField()     ) ).values('str_datetime').first() 

The result is:

foo_bar.str_datetime: (str)'Days: 28 Hours: 15' 
like image 23
Eugene Kovalev Avatar answered Oct 11 '22 12:10

Eugene Kovalev