Login

DateTimeField with microseconds

Author:
tobias
Posted:
February 26, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

Use this in your form if you want to accept input in microseconds.

In a ModelForm you can override the field like this:

def __init__(self, *arg, **kwargs):
    super(MyForm, self).__init__(*arg, **kwargs)
    self.fields['date'] = DateTimeWithUsecsField()

Update May 26 2009 - Updated to address a couple issues with this approach. See http://code.djangoproject.com/ticket/9459

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class DateTimeWithUsecsField(forms.DateTimeField):
    def clean(self, value):
        if value and '.' in value: 
            value, usecs = value.rsplit('.', 1) # rsplit in case '.' is used elsewhere
            usecs += '0'*(6-len(usecs)) # right pad with zeros if necessary
            try:
                usecs = int(usecs) 
            except ValueError: 
                raise ValidationError('Microseconds must be an integer') 
        else: 
            usecs = 0 
        cleaned_value = super(DateTimeWithUsecsField, self).clean(value)
        if cleaned_value:
            cleaned_value = cleaned_value.replace(microsecond=usecs)
        return cleaned_value

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.