Django - Need datetime fields that can handle only year, or year and month values

10,495

Maybe this would help:

DayMonthField and YearField

django-yearlessdate - https://github.com/seddonym/django-yearlessdate

YearMonthField

YEARMONTH_INPUT_FORMATS = (
    '%Y-%m', '%m/%Y', '%m/%y', # '2006-10', '10/2006', '10/06'
)

class YearMonthField(CharField):
    default_error_messages = {
        'invalid': _('Enter a valid year and month.'),
    }

    def __init__(self, input_formats=None, *args, **kwargs):
        super(YearMonthField, self).__init__(*args, **kwargs)
        self.input_formats = input_formats

    def clean(self, value):
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return format(value, '%Y-%m')
        if isinstance(value, datetime.date):
            return format(value, '%Y-%m')
        for fmt in self.input_formats or YEARMONTH_INPUT_FORMATS:
            try:
                date = datetime.date(*time.strptime(value, fmt)[:3])
                return format(date, '%Y-%m')
            except ValueError:
                continue
        raise ValidationError(self.error_messages['invalid'])

class MyModel(models.Model):
    yearmonth = YearMonthField() 
Share:
10,495
kimg85
Author by

kimg85

Updated on June 24, 2022

Comments

  • kimg85
    kimg85 almost 2 years

    I need to be able to only write year, or year and month (in addition to the standard full datetime values) in some of my datetime fields. Like these patterns below.

    YYYY
    YYYY-MM
    YYYY-MM-DD
    YYYY-MM-DD HH
    YYYY-MM-DD HH:MM
    YYYY-MM-DD HH:MM:SS
    

    In mySQL this can easily be done by using zeroes, but that dos not work in django. It`s that stupid time.datetime python function that dos not support it.

    Is there some easy way of doing this in django? If not, are there some extensions that can do this for me? If not, how do I solve this in the best possible way?

    I would be nice if it could deal normalizing of local time stuff if it was a full data time value. That way I could use the same field everywhere. But it is not super important.

  • catherine
    catherine about 11 years
    if you have question, I will answer it tomorrow. Need to sleep
  • Abhishek Bhatia
    Abhishek Bhatia over 7 years
    Hi! When I implemented this it showed me (fields.E120) CharFields must define a 'max_length' attribute.. Any suggestions?
  • MrVocabulary
    MrVocabulary almost 7 years
    @Abhishek Bhatia you need to put max_length = 100 (or whatever number) for each CharField. Django requires you to use this parameter, like that: var = model.CharField(max_length = 100)