Python中如何使用arrow库像PHP那样设定一个全局时区
需求是这样。 考虑到多国语言,数据库中存储的都是 utc 时间。
现在用来做格式化显示必须是arrow.get(timestamp).to(current_tz).format()来进行显示。能不能像 php 那样date_default_timezone_set($tz)在某个部分做一次全局时区设置,例如上下文。
Python中如何使用arrow库像PHP那样设定一个全局时区
1 回复
在Python的arrow库中,可以通过arrow.utcnow().to(‘Asia/Shanghai’)这样的方式转换时区,但如果你想像PHP的date_default_timezone_set()那样设置全局时区,arrow本身没有直接提供这个功能。
不过你可以通过猴子补丁(monkey-patching)的方式来实现类似效果:
import arrow
from datetime import datetime
import pytz
# 设置全局时区
GLOBAL_TIMEZONE = 'Asia/Shanghai'
# 创建自定义的now函数
def custom_now(tz=GLOBAL_TIMEZONE):
return arrow.utcnow().to(tz)
# 替换arrow.now
arrow.now = custom_now
# 使用示例
print(f"当前时间(全局时区): {arrow.now()}")
print(f"格式化显示: {arrow.now().format('YYYY-MM-DD HH:mm:ss')}")
# 也可以创建特定时间的对象
dt = arrow.get('2023-01-01 12:00:00', tzinfo=GLOBAL_TIMEZONE)
print(f"特定时间: {dt}")
另一种更干净的方法是创建一个时区上下文管理器:
import arrow
from contextlib import contextmanager
class ArrowWithGlobalTimezone:
def __init__(self, timezone='Asia/Shanghai'):
self.timezone = timezone
def now(self):
return arrow.utcnow().to(self.timezone)
def get(self, *args, **kwargs):
if 'tzinfo' not in kwargs:
kwargs['tzinfo'] = self.timezone
return arrow.get(*args, **kwargs)
# 使用
arrow_tz = ArrowWithGlobalTimezone('Asia/Shanghai')
print(arrow_tz.now())
print(arrow_tz.get('2023-01-01 12:00:00'))
如果你想要更彻底的全局设置,可以考虑在应用启动时设置环境变量:
import os
os.environ['TZ'] = 'Asia/Shanghai'
但这种方法会影响所有datetime操作,不仅仅是arrow。
总结:用猴子补丁或封装类来模拟全局时区。

