You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取America/Los_Angeles格式的当前时区城市名称

如何获取America/Los_Angeles格式的当前时区城市名称

嘿,这个问题我之前踩过坑!strftime里的%z和%Z确实只能输出时区偏移(比如+0800)或者缩写(比如PST),没法直接拿到像America/Los_Angeles这种标准的IANA时区标识符。不过不同编程语言都有对应的解决方案,我给你列几个常用场景的实现:

Python 实现

  • 如果你用的是Python 3.9及以上版本,自带的zoneinfo模块就能搞定,不用额外装包:
    from zoneinfo import ZoneInfo
    from datetime import datetime
    
    # 获取当前系统的IANA时区名称
    current_timezone = datetime.now().astimezone().tzinfo.key
    print(current_timezone)  # 输出示例:America/Los_Angeles
    
  • 要是用的是旧版Python,可以借助tzlocal第三方库(先跑pip install tzlocal安装):
    from tzlocal import get_localzone
    
    current_timezone = get_localzone().key
    print(current_timezone)
    

JavaScript 实现

  • 浏览器环境下,用Intl API就能轻松获取:
    const currentTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    console.log(currentTimezone); // 输出示例:America/Los_Angeles
    
  • Node.js环境里除了上面的方法,还可以直接读取环境变量(如果配置了的话):
    const currentTimezone = process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone;
    console.log(currentTimezone);
    

本质上,strftime本身没有提供获取IANA时区的能力,你需要依赖语言自带的时区处理工具或者第三方库来实现这个需求。

备注:内容来源于stack exchange,提问作者thang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 08:23:14