如何在其他区域设置strftime日期对象? [英] How do I strftime a date object in a different locale?
问题描述
我在python中有一个date对象,我需要使用%a(工作日)和%b(月)代码在C语言环境中为旧版系统生成一个时间戳.但是,我不希望更改应用程序的语言环境,因为其他部分需要尊重用户的当前语言环境.有没有一种方法可以使用特定语言环境来调用strftime()?
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 change the application's locale, since other parts need to respect the user's current locale. Is there a way to call strftime() with a certain locale?
推荐答案
Rob给出的示例很好,但不是线程安全的.这是与线程配合使用的版本:
The example given by Rob is great, but isn't threadsafe. Here's a version that works with threads:
import locale
import threading
from datetime import datetime
from contextlib import contextmanager
LOCALE_LOCK = threading.Lock()
@contextmanager
def setlocale(name):
with LOCALE_LOCK:
saved = locale.setlocale(locale.LC_ALL)
try:
yield locale.setlocale(locale.LC_ALL, name)
finally:
locale.setlocale(locale.LC_ALL, saved)
# Let's set a non-US locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
# Example to write a formatted English date
with setlocale('C'):
print(datetime.now().strftime('%a, %b')) # e.g. => "Thu, Jun"
# Example to read a formatted English date
with setlocale('C'):
mydate = datetime.strptime('Thu, Jun', '%a, %b')
它使用全局锁创建线程安全上下文管理器,并允许您使用LOCALE_LOCK使多个线程运行与语言环境相关的代码.它还处理yield语句中的异常,以确保始终还原原始语言环境.
It creates a threadsafe context manager using a global lock and allows you to have multiple threads running locale-dependent code by using the LOCALE_LOCK. It also handles exceptions from the yield statement to ensure the original locale is always restored.
这篇关于如何在其他区域设置strftime日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!