Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strftime on a django datetime produces a UTC time in the string

I have the following code in one of my models:

def shortDescription(self):
    return self.name + ' ' + self.class_date.strftime("%I:%M")

self.class_date is a timezone aware DateTimeField, self.class_date.is_aware() is True, USE_TZ is True.

The shortDescription returns a string that gives the time in UTC rather than the default timezone, putting {{ aclass.class_date }} in the template displays the time in the correct zone.

Is strftime always working on the base, native time? Or what else is going on here?

like image 765
Rob Osborne Avatar asked Aug 10 '12 20:08

Rob Osborne


People also ask

What is the format of datetime in Django?

And, because the format is dd/mm/yyyy, we must use a slash to separate the date, month and year.

What is Strftime in Python?

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Syntax : strftime(format) Returns : It returns the string representation of the date or time object.

How do I use datetime in Django?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value. Now, we can either assign this method to a variable or we can directly use this method wherever we required the datetime value.


1 Answers

When you directly reference pieces of the datetime like %I or %M, it uses it straight as it is with no locale conversion. If you included %Z you'd see that the time is in UTC. If you want locale-aware results, you need use the more limited %X, which will simply spit out the full time converted for the locale.

If you need more, you'll have to convert it:

from django.utils import timezone

def shortDescription(self):
    class_date = timezone.localtime(self.class_date)
    return self.name + ' ' + class_date.strftime("%I:%M")

Or, you can rely on the date filter, which automatically does this for you:

from django.template import defaultfilters

def shortDescription(self):
    return self.name + ' ' + defaultfilters.date(self.class_date, 'g:i')
like image 64
Chris Pratt Avatar answered Oct 21 '22 22:10

Chris Pratt