我在 python 中有一个日期对象,我需要使用 %a (工作日)和 %b (月份)代码在旧系统的 C 语言环境中生成时间戳。但是,我不想更改应用程序的区域设置,因为其他部分需要尊重用户当前的区域设置。有没有办法在特定区域设置下调用 strftime() ?
Rob 给出的例子很棒,但不是线程安全的。这是一个适用于线程的版本:
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 语句的异常,以确保始终恢复原始语言环境。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)