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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With