Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django localized date parsing

I have a django application that is completly internationalized and we are using date fields that also should be in the format of the respective language. Now I've got the problem that I must parse different date formats based on the current language.

I've tried this:

from django.utils import formats, translation
format_code = formats.get_format("SHORT_DATE_FORMAT", lang=translation.get_language())

It returns the currently used date format (e.g. "d.m.Y" for Germany) but I need it in a date format I can parse with datetime.strptime (e.g. "%d.%m.%Y"). How can I get this?

like image 799
Lilith Wittmann Avatar asked Sep 06 '25 19:09

Lilith Wittmann


1 Answers

Currently, the best way I found is this:

from datetime import datetime
from django.utils import formats

def parse_locale_date(formatted_date):
    parsed_date = None
    for date_format in formats.get_format('DATE_INPUT_FORMATS'):
        try:
            parsed_date = datetime.strptime(formatted_date, date_format)
        except ValueError:
            continue
        else:
            break
    if not parsed_date:
        raise ValueError
    return parsed_date.date()
like image 80
Antoine Pinsard Avatar answered Sep 09 '25 21:09

Antoine Pinsard