39

我在 python 中有一个日期对象,我需要使用 %a (工作日)和 %b (月)代码在 C 语言环境中为遗留系统生成时间戳。但是我不希望更改应用程序的语言环境,因为其他部分需要尊重用户当前的语言环境。有没有办法用特定的语言环境调用 strftime() ?

4

3 回答 3

47

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 语句的异常,以确保始终恢复原始语言环境。

于 2014-06-05T21:41:50.227 回答
18

不,无法strftime()使用特定的语言环境进行调用。

假设您的应用程序不是多线程的,请保存并恢复现有的语言环境,并将您的语言环境设置为'C'当您调用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'))

如果你喜欢with:- try:finally:你可以启动一个上下文管理器:

#! /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'))
于 2013-09-03T13:53:58.220 回答
-5

看看pytz 包

你可以这样使用

import pytz
UTC = pytz.timezone('UTC') # utc
fr = pytz.timezone('Europe/Paris') #your local
from datetime import datetime
date = datetime.now(fr)
dateUTC = date.astimezone(UTC)

strftime 将在指定的时区呈现

对于在语言环境中有月份名称使用日历,例如:

import calendar
print calendar.month_name[dateUTC.month] #will print in the locale

更深入地检查日历以获得更多信息

于 2013-09-03T13:38:57.003 回答