Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 349
kimg85 Avatar asked Mar 10 '13 17:03

kimg85


1 Answers

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() 
like image 175
catherine Avatar answered Nov 03 '22 07:11

catherine