Search code examples
pythondatetimeformatdatetime-format

How to create new date format for datetime to use?


I am quite new to programming so please excuse if I don't use the correct terms.

I want to convert a list of dates into another format. Until now it was easy because the dates that I had to convert were in this format: %d-%b-%Y (example 13-Jan-2023). So I could just "tell" python that it was in this format and that it should convert it to : %d/%m/%Y (example 13/01/2023).

However, the initial date format has changed to 13-janv.-2023 (per example), so the months are now in french and abbreviated (janv. ; févr. ; mars ; avr. ; mai ; juin ; juil. ; sept. ; oct. ; nov. ; déc.

I can imagine that there must be a way to define a dictionary such as "Jan : janv. ", and then define it as a new format but I have not succeeded yet. Your help will be appreciated.

Thanks

I am sorry, I have not found a similar question...


Solution

  • localeis your friend for region-specific topics.

    from datetime import datetime as dt
    import locale
    
    
    locale.setlocale(locale.LC_TIME, "fr_FR")
    date_fr = '13-janv.-2023'
    dt.strptime(date_fr, '%d-%b-%Y').strftime('%d/%m/%Y')
    

    Returns your desired result. But be aware! After setting your locale, you can't parse your initial ('13-Jan-2023') format anyore until your change the locale back.

    Explanation:
    strptime is to parse your input, hence the p in the function name
    strftime is to format your date/time, hence the f.