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

前端 未结 1 530
南笙
南笙 2021-02-19 05:32

I have the following code in one of my models:

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

<

1条回答
  •  独厮守ぢ
    2021-02-19 06:28

    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')
    

    0 讨论(0)
提交回复
热议问题