In PostgreSQL database timestamp
datatype column has value as:
2018-06-08 12:35:09
But when retrieving data using django, data is returned as (datetime is combining microseconds):
"2018-06-08T12:35:09.225"
How can I convert this datetime object to "DD-MM-YYYY HH:MM:SS" format in django?
Note - I am using CookieCutter
Code I am using to retrieve data from Model Bid
is as below (views.py
):
request_data = json.loads(request.body)
bidId = request_data['id']
bidData = Bid.objects.get(bid_id=bidId)
data = serializers.serialize('json', [bidData, ])
serialized = json.loads(data)
bid_obj = json.loads(serialized[0]['fields']['bid_obj'])
serialized[0]['fields']['bid_obj'] = bid_obj
outputArray = {
"bid": serialized[0]['fields']
}
return JsonResponse(outputArray, safe=False)
As you have found out, the datetime
object that is retrieved contains microseconds. If you don't want to display the microseconds, or any other part of the datetime
object, you can use the method strftime
and pass the desired format.
In your case the desired format is DD-MM-YYYY HH:MM:SS. You can get that format in python with the following snippet:
dt.strftime('%d-%m-%Y %H:%M:%S')
It is assumed that the variable dt
is a datetime
object.
In the official documentation you can see which other options you can pass to strftime
.