Skip to content

Instantly share code, notes, and snippets.

@elnygren
Last active March 8, 2019 02:39
Show Gist options
  • Save elnygren/da7a1b7496a598f95bc8d8277f420b2d to your computer and use it in GitHub Desktop.
Save elnygren/da7a1b7496a598f95bc8d8277f420b2d to your computer and use it in GitHub Desktop.
ISO 8601 with timezone (2018-05-01T10:48:30+00:00) support for Django
from django import forms
from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_str
from django.forms.widgets import DateTimeInput
from django.utils.translation import gettext_lazy as _, ngettext_lazy
class ISODateTimeField(forms.Field):
"""DateTimeField that uses django.utils.dateparse.parse_datetime.
More precisely, this DateTimeField accepts ISO 8601 datetime strings
that specify timezone with +00:00 syntax.
https://en.wikipedia.org/wiki/ISO_8601
https://code.djangoproject.com/ticket/11385
https://bugs.python.org/issue15873
https://bugs.python.org/msg169952
"""
widget = DateTimeInput
default_error_messages = {
'invalid': _('Enter a valid date/time.'),
}
def to_python(self, value):
value = value.strip()
try:
return self.strptime(value, format)
except (ValueError, TypeError):
raise forms.ValidationError(self.error_messages['invalid'], code='invalid')
def strptime(self, value, format):
return parse_datetime(force_str(value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment