How do I strftime a date object in a different locale?

前端 未结 3 542
半阙折子戏
半阙折子戏 2020-11-29 05:58

I have a date object in python and I need to generate a time stamp in the C locale for a legacy system, using the %a (weekday) and %b (month) codes. However I do not wish to

3条回答
  •  孤城傲影
    2020-11-29 06:25

    No, there is no way to call strftime() with a specific locale.

    Assuming that your app is not multi-threaded, save and restore the existing locale, and set your locale to 'C' when you invoke strftime.

    #! /usr/bin/python3
    import time
    import locale
    
    
    def get_c_locale_abbrev():
      lc = locale.setlocale(locale.LC_TIME)
      try:
        locale.setlocale(locale.LC_TIME, "C")
        return time.strftime("%a-%b")
      finally:
        locale.setlocale(locale.LC_TIME, lc)
    
    # Let's suppose that we're french
    locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
    
    # Should print french, english, then french
    print(time.strftime('%a-%b'))
    print(get_c_locale_abbrev())
    print(time.strftime('%a-%b'))
    

    If you prefer with: to try:-finally:, you could whip up a context manager:

    #! /usr/bin/python3
    import time
    import locale
    import contextlib
    
    @contextlib.contextmanager
    def setlocale(*args, **kw):
      saved = locale.setlocale(locale.LC_ALL)
      yield locale.setlocale(*args, **kw)
      locale.setlocale(locale.LC_ALL, saved)
    
    def get_c_locale_abbrev():
      with setlocale(locale.LC_TIME, "C"):
        return time.strftime("%a-%b")
    
    # Let's suppose that we're french
    locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
    
    # Should print french, english, then french
    print(time.strftime('%a-%b'))
    print(get_c_locale_abbrev())
    print(time.strftime('%a-%b'))
    

提交回复
热议问题