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

如何用Python的zoneinfo库从datetime对象中提取时区偏移?

如何从Python的datetime对象中提取时区偏移(如-04:00)

我用Python的datetime和zoneinfo库获取全球各地的日期时间,已经能单独提取日、月、年、时、分、秒、微秒等部分,但不知道怎么从datetime变量里提取时区偏移部分(比如从2024-07-01 17:32:11.454840-04:00中获取-04:00)。

以下是我的部分代码:

import datetime
import zoneinfo

zonaNewYork = zoneinfo.ZoneInfo('America/New_York')

fechaHora_NewYork = datetime.datetime.now(zonaNewYork)
print(type(fechaHora_NewYork))
print("Fecha y Hora en NewYork, EEUU: ")
print(fechaHora_NewYork, "\n")


###### Get Time individually
hora = fechaHora_NewYork.hour
print("Hora: ", hora, "\n")

minutos = fechaHora_NewYork.minute
print("Minutos: ", minutos, "\n")

segundos = fechaHora_NewYork.second
print("Segundos: ", segundos, "\n")

microsegundos = fechaHora_NewYork.microsecond
print("Microsegundos: ",microsegundos, "\n")


###### Get Date individually
year = horafecha_actual.year
print("Año: ", year, "\n")

mes = horafecha_actual.month
print("Mes: ", mes, "\n")

dia = horafecha_actual.day
print("Día: ", dia, "\n")

代码输出:

<class 'datetime.datetime'>
Fecha y Hora en NewYork, EEUU:
2024-07-01 17:32:11.454840-04:00

Hora:  17

Minutos:  32

Segundos:  11

Microsegundos:  454840

Año:  2024

Mes:  7

Día:  1

解决方法

有两种简单方式可以提取目标格式的时区偏移:

方法1:利用strftime格式化

通过datetime对象的strftime方法,用%z格式符获取不带冒号的偏移字符串(如-0400),再手动插入冒号转换成-04:00格式:

# 获取不带冒号的原始偏移字符串
offset_raw = fechaHora_NewYork.strftime("%z")
# 转换成带冒号的目标格式
offset_formatted = f"{offset_raw[:3]}:{offset_raw[3:]}"
print("时区偏移:", offset_formatted)

方法2:通过utcoffset计算偏移

先获取datetime对象与UTC的时间差(timedelta类型),再计算小时和分钟,最后格式化为目标字符串:

# 获取UTC偏移量
utc_offset = fechaHora_NewYork.utcoffset()
# 计算总秒数
total_seconds = int(utc_offset.total_seconds())
# 拆分小时和分钟
hours = total_seconds // 3600
minutes = abs(total_seconds % 3600) // 60
# 格式化为带冒号的字符串
offset_formatted = f"{hours:+03d}:{minutes:02d}"
print("时区偏移:", offset_formatted)

两种方法都能输出你需要的-04:00格式时区偏移。

内容的提问来源于stack exchange,提问作者Jdavid_Ar08

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:02:46