Checks the type of the field (date / time / date-time) and returns corresponding value as a string.
1 2 3 4 5 6 7 8 9 10 | def convertDatetimeToString(o):
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S"
if isinstance(o, datetime.date):
return o.strftime(DATE_FORMAT)
elif isinstance(o, datetime.time):
return o.strftime(TIME_FORMAT)
elif isinstance(o, datetime.datetime):
return o.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT))
|
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 2 weeks ago
- get_object_or_none by azwdevops 5 months, 1 week ago
- Mask sensitive data from logger by agusmakmun 7 months ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
Comments
Hello,
I am using the function, but I do not know why isinstance(o, datetime.time) is returning false, when it should be true. My model has a DateTimeField attribute:
-----------------------------------------------------
class Measure (models.Model):
----------------------------------------------------
On the shell:
2011-11-01 01:18:27
2011-11-01
#
You put
.daterather than.datetimeafter the field which converts the datetime.datetime object (a DateTimeField in your db) into a datetime.date object. Adateobject doesn't contain time information and it doesn't inherit the datetime class, so the isinstance doesn't match datetime.datetime. Try doing type(obj) whenever you want to know what type an object is.#
Please login first before commenting.