Login

FuzzyDateTimeField

Author:
japerk
Posted:
April 9, 2009
Language:
Python
Version:
1.0
Tags:
datetime humanize
Score:
0 (after 0 ratings)

FuzzyDateTimeField is a drop in replacement for the standard DateTimeField that uses dateutil.parser to clean the value. It has an extra keyword argument fuzzy=True, which allows it to be more liberal with the input formats it accepts. Set fuzzy=False for more strict validation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from django import forms
import dateutil.parser

class FuzzyDateTimeField(forms.Field):
	'''Like a DateTimeField, but uses dateutil.parser to parse datetime.'''
	def __init__(self, widget=forms.DateTimeInput, fuzzy=True, **kwargs):
		forms.Field.__init__(self, widget=widget, **kwargs)
		self.fuzzy = fuzzy
	
	def clean(self, val):
		super(FuzzyDateTimeField, self).clean(val)
		
		if not val:
			return None
		elif isinstance(val, datetime.datetime):
			return val
		
		try:
			return dateutil.parser.parse(val.strip(), fuzzy=self.fuzzy)
		except ValueError, err:
			raise forms.ValidationError(*err.args)

More like this

  1. Fuzzy testing with assertNumQueries by spookylukey 4 years, 7 months ago
  2. Smart i18n date diff (twitter like) by Batiste 6 years, 5 months ago
  3. Fuzzy Time of Day by waylan 8 years, 2 months ago
  4. DateTimeField with microseconds by tobias 6 years, 6 months ago
  5. Fuzzy Date Diff Template Filter by zain 6 years, 6 months ago

Comments

Please login first before commenting.