Advertisement
Guest User

DateTimeNoTimeZoneField

a guest
Nov 5th, 2013
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. import datetime
  2. from django import forms
  3. from django.core import validators
  4. from django.core.exceptions import ValidationError
  5. from django.utils import six
  6. from django.utils.encoding import force_text
  7.  
  8.  
  9. class DateTimeNoTimeZoneField(forms.DateTimeField):
  10.     def to_python(self, value):
  11.         """
  12.        Validates that the input can be converted to a datetime. Returns a
  13.        Python datetime.datetime object.
  14.        """
  15.         if value in validators.EMPTY_VALUES:
  16.             return None
  17.         if isinstance(value, datetime.datetime):
  18.             return value
  19.         if isinstance(value, datetime.date):
  20.             return datetime.datetime(value.year, value.month, value.day)
  21.         if isinstance(value, list):
  22.             # Input comes from a SplitDateTimeWidget, for example. So, it's two
  23.             # components: date and time.
  24.             if len(value) != 2:
  25.                 raise ValidationError(self.error_messages['invalid'])
  26.             if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
  27.                 return None
  28.             value = '%s %s' % tuple(value)
  29.                 # Try to coerce the value to unicode.
  30.         unicode_value = force_text(value, strings_only=True)
  31.         if isinstance(unicode_value, six.text_type):
  32.             value = unicode_value.strip()
  33.         # If unicode, try to strptime against each input format.
  34.         if isinstance(value, six.text_type):
  35.             for format in self.input_formats:
  36.                 try:
  37.                     return self.strptime(value, format)
  38.                 except (ValueError, TypeError):
  39.                     continue
  40.         raise ValidationError(self.error_messages['invalid'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement