如何在Python 3中获取本地IANA时区名称
获取Python 3本地IANA时区名称的原生方案
要获取系统的IANA时区名称(如Australia/Sydney),且满足仅使用Python原生模块、不调用外部命令的要求,可通过读取系统时区配置文件的方式实现,以下是兼容RedHat 7/8/9和Ubuntu的解决方案:
实现代码
import os from pathlib import Path import zoneinfo def get_local_iana_timezone(): # 读取Ubuntu系统的/etc/timezone文件(直接存储IANA时区名) timezone_file = Path("/etc/timezone") if timezone_file.exists(): with open(timezone_file, "r") as f: tz_name = f.read().strip() if tz_name in zoneinfo.available_timezones(): return tz_name # 处理RedHat系列:解析/etc/localtime的软链接目标 localtime_link = Path("/etc/localtime") if localtime_link.is_symlink(): tz_path = localtime_link.resolve() # 从路径中提取IANA时区名称,例如从/usr/share/zoneinfo/Australia/Sydney提取后半段 tz_name = str(tz_path).split("/zoneinfo/")[-1] if tz_name in zoneinfo.available_timezones(): return tz_name # 备选方案:读取环境变量TZ tz_env = os.environ.get("TZ") if tz_env and tz_env in zoneinfo.available_timezones(): return tz_env return None # 使用示例 local_tz = get_local_iana_timezone() print(local_tz)
代码说明
- Ubuntu适配:直接读取
/etc/timezone文件,该文件内存储的就是标准IANA时区名称 - RedHat适配:
/etc/localtime是指向/usr/share/zoneinfo/目录下对应时区文件的软链接,解析链接路径后提取出时区名称 - 有效性验证:所有获取到的时区名称都会通过
zoneinfo.available_timezones()校验,确保是合法的IANA时区 - 备选方案:若以上方式失效,尝试读取环境变量
TZ的值
注意事项
- 确保脚本具备读取
/etc/timezone和/etc/localtime的权限 - 该方案兼容主流的RedHat 7/8/9和Ubuntu服务器版本
内容的提问来源于stack exchange,提问作者Ramanan T
相关产品推荐
相关产品推荐

