Python datetimes and Django’s humanize

(Originally posted July 16, 2013)

One of the important things to know when dealing with deadlines is how long you have left to complete them. The complete, but very annoying to deal with, python datetime module is able to calculate these times. But displaying them on a webpage isn’t exactly pleasing to the eye. For example:

5 days, 10:14:57.121807

is what it would look like if you just printed it out. This is fine if your looking for pure information, but not good at all for anything in production since it takes longer than half a second to figure out, and we don’t want users to have to think very hard about something like this. Luckily, Django has template filters in their “humanize” library that converts unpleasing text like that into something human readable. To do this, all you do is throw a filter after the time and you should get the humanized time instead. If I returned the time difference between the final time and the current time,

1
2
time_difference = end_time - cur_time
return time_difference

I should be able to run that through the filter and get the desired format.

{{time_difference|naturaltime}}

Unfortunately, for the code I was using, this wasn’t working. The filter didn’t have any effect on the time object. Time to dig into Django’s source code. After finding the humanize file, the first thing I noticed was

1
2
if not isinstance(value, date): # datetime is a subclass of date
    return value

This check makes sure that the value being passed in the filter is of type date, or datetime. Since I was returning a difference of datetimes, I was actually passing a timedelta object, which would fail this check and return the original value, which was the error I was getting. Like I said, python datetimes are annoying.

To fix this error, I simply had to make sure that my function returned a datetime. Since a datetime – timedelta returns a datetime, I changed my code to

1
2
time_difference = end_time - cur_time
return cur_time + time_difference

And just like that, the filter was working as expected. Kind of a silly error considering that when you use the naturaltime filter, you’re always going to end up with a timedelta, so you should be able to use one off the bat. Either way, humanizing the times is way better than the clunky normal time display.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s