简体   繁体   中英

How to get datetime as string from mysql database in django model query

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM