Home Web Development Django Solution to: How do I convert a Django TimeField object to a...

Get social!

Let’s say you have a Django TimeField in a model object called event.start_time. You want to convert it to a string for displaying. Assume the time is 10:30 in the morning and you want to display it like so: “10:30 a.m.”. If you were using a Django template, you could implement the time filter like so:


However, in my case I’m not using a template. I need the string for part of a PDF I’m outputting.


Since Django’s TimeField object is also a Python datetime.time object, you can use the object’s strftime() method to convert to a formatted string:


And there you have it. The above code will produce the same formatted string as the Django template time filter (“10:30 a.m.”).

Note: Python’s date and time format specifiers are not the same as Django’s. Django uses the same specifier’s as PHP’s date() function, for the most part. I wonder what the justification is for that design decision?

You can find the Python date specifiers (for strftime()) here:


For Django’s template time filter format specifiers, look here (the date and time filters use the same specifiers):


Bad Behavior has blocked 51 access attempts in the last 7 days.