2👍
✅
You could use this function to convert dates:
import re
def parse_slash_date(value):
m = re.match(r'^(?P<day>[0-9]{1,2})/(?P<month>[0-9]{1,2})/(?P<year>[0-9]{4})$', value)
if m:
return '%s-%s-%s' % (
m.group('year'), m.group('month'), m.group('day'))
Example:
In [4]: parse_slash_date('06/10/2012')
Out[4]: '2012-10-06'
You could also create a DateField that uses the parser:
class YourDateField(models.DateField):
def get_prep_lookup(self, lookup_type, value):
if value and '/' in value:
value = parse_slash_date(value)
return super(YourDateField, self).get_prep_lookup(
lookup_type, value)
However, I was pretty sure that DateField was able to parse dates with slashes already… But I just read the code of django.utils.dateparse.parse_date and it doesn’t.
👤jpic
Source:stackexchange.com