Skip to content

Instantly share code, notes, and snippets.

Created July 3, 2014 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/78d0962d0260f27637da to your computer and use it in GitHub Desktop.
Save anonymous/78d0962d0260f27637da to your computer and use it in GitHub Desktop.
class LocalDateTimeField(with_metaclass(models.SubfieldBase, models.DateTimeField)):
'''A hack/workaround version of DateTimeField that considers the datetime
from the database as local time.
'''
def to_python(self, value):
from django.utils.dateformat import format
value = models.DateTimeField.to_python(self, value)
if isinstance(value, datetime):
print('-' + repr(value))
print(strftime('%Y-%m-%d %H:%M:%S.%f', value.timetuple()))
print(format(value, 'd F Y, H:i'))
value = value.replace(tzinfo=get_default_timezone())
print('+' + repr(value))
print(strftime('%Y-%m-%d %H:%M:%S.%f', value.timetuple()))
print(format(value, 'd F Y, H:i'))
return value
# I have a model with a LocalDateTimeField.
obj = MyModel.objects.get(id=1234)
repr(obj.datefield)
# datetime.datetime(2014, 7, 3, 17, 7, 3, tzinfo=<DstTzInfo 'America/Sao_Paulo' LMT-1 day, 20:54:00 STD>)
from django.template import Context,Template
templ = Template('Date: {{ d|date:"d F Y, H:i:s" }}')
templ.render(Context({'d': obj.datefield}))
# 'Date: 03 July 2014, 17:13:03'
# WTF?
# Why the object is 17:07:03 and the printed version from the template is 17:13:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment