1

I am using below query to get fields from mysql database in django 1.9.

event_dict_list = EventsModel.objects.filter(name__icontains = event_name).values('sys_id','name', 'start_date_time', 'end_date_time', 'notes')

now in the result event_dict_list, start_date_time and end_date_time are appearing in python date time object format as below

'end_date_time': datetime.datetime(2016, 9, 26, 10, 48, 35, tzinfo=<UTC>)

I want it as a string in YYYY-mm-dd HH:MM:SS format.

One way would be to iterate over the event_dict_list and get date field and then convert it into desired string format. But I wanted to know if there is any way I can specify something in query so that I get the converted date in query output only?

Related question - what is preferred way to store date/datetime in database - as python date time or as string. Way 1 or way 2.
(1) end_date_time = models.DateTimeField(null=False, blank=False)
(2) end_date_time = models.CharField(max_length= 128, null=False, blank=False)

Anurag Rana
  • 1,429
  • 2
  • 24
  • 48

1 Answers1

0

You could try using the CAST() command in your query: Convert DateTime Value into String in Mysql

The above example kinda shows you how to!

If that doesnt work, the other option is as you stated, iterate over your dates and times and convert as shown here: Convert datetime object to a String of date only in Python

Community
  • 1
  • 1
BLang
  • 930
  • 3
  • 16
  • 35