Display date and time in local language in Python

  • To display a specified date in local language and format, we have to use the python library locale. Identify the correct locale code for each country and use it directly as below.

    As seen in the sample, based on the locale applied, language as well as the display format changes for the mentioned date. Also note that, locale code are different for different OS as well.

    Copied
    from  datetime import datetime
    from sys import platform
    import locale
    
    if platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'en_US')
    else:
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    
    dt = datetime(2022, 1, 15, 20, 40, 50)
    
    print("#####English US#####")
    print("Date: " + dt.strftime("%B-%d-%Y"))
    print("Time: " + dt.strftime("%X"))
    print("Weekday: " + dt.strftime("%A"))
    
    if platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'de_DE')
    else:
        locale.setlocale(locale.LC_ALL, 'de_DE.ISO8859-1')
    
    print("#####German#####")
    print("Date: " + dt.strftime("%B-%d-%Y"))
    print("Time: " + dt.strftime("%X"))
    print("Weekday: " + dt.strftime("%A"))
    
    Output:
      #####English US#####
      Date: January-15-2022
      Time: 8:40:50 PM
      Weekday: Saturday

      #####German#####
      Date: Januar-15-2022
      Time: 20:40:50
      Weekday: Samstag

    Identifying the right locale code is the major challenge here.
    To list all the codes, we can run the code locale.locale_alias after importing locale.

Absolute Code Works - Python Topics