def _to_python(self, value, state): """Parse a string and return a datetime object.""" if value and isinstance(value, datetime): return value else: try: format = self.format if callable(format): format = format() tpl = time.strptime(value, format) except ValueError: raise Invalid(self.message('badFormat', state), value, state) # shoudn't use time.mktime() because it can give OverflowError, # depending on the date (e.g. pre 1970) and underlying C library return datetime(year=tpl.tm_year, month=tpl.tm_mon, day=tpl.tm_mday, hour=tpl.tm_hour, minute=tpl.tm_min, second=tpl.tm_sec)
def _from_python(self, value, state): """Return a string representation of a datetime object.""" if not value: return None elif isinstance(value, datetime): # Python stdlib can only handle dates with year greater than 1900 format = self.format if callable(format): format = format() if format is None: format = "%Y-%m-%d" if value.year <= 1900: return strftime_before1900(value, format) else: return value.strftime(format) else: return value