Alberto Villacorta
Alberto Villacorta

Reputation: 81

django convert .values_list('datetimefield') to date

I would like to convert a a values_list field with a datetime object to a date object.

.values_list('time_finished', flat=True)

gives me "2016-03-22T18:52:53.486Z" and what I would like is "2016-03-22"

Thank you!

Upvotes: 2

Views: 4374

Answers (2)

AKS
AKS

Reputation: 19811

You can use extra to run some database functions directly such as using DATE:

queryset = queryset.extra(select={'time_finished_date': 'DATE(time_finished)'}).values_list('time_finished_date', flat=True)

If you print the SQL query from the queryset, it will look something like this:

>>> print(queryset.query)
# SELECT (DATE(time_finished)) AS "time_finished_date" FROM <<tablename>>

Upvotes: 5

falsetru
falsetru

Reputation: 369054

You can use datetime.datetime.date() method to get datetime.date object:

>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2016, 4, 12, 15, 54, 48, 401418)
>>> dt.date()
datetime.date(2016, 4, 12)

Use datetime.datetime.strftime to get string:

>>> dt.strftime('%Y-%m-%d')
'2016-04-12'

[dt.date() for dt in query.values_list('time_finished', flat=True)]

Upvotes: 6

Related Questions