gpt4 book ai didi

Python - 从 DST 调整的本地时间到 UTC

转载 作者:太空狗 更新时间:2023-10-29 21:38:09 24 4
gpt4 key购买 nike

一家特定的银行在世界所有主要城市都设有分支机构。它们都在本地时间上午 10:00 开放。如果在使用夏令时的时区内,那么本地的开放时间当然也遵循夏令时调整后的时间。那么我如何从本地时间转到 utc 时间。

我需要的是这样一个函数to_utc(localdt, tz):

参数:

  • localdt:本地时间,作为原始日期时间对象,经过 DST 调整
  • tz:TZ 格式的时区,例如'欧洲/柏林'

返回:

  • 日期时间对象,UTC,时区感知

编辑:

最大的挑战是检测本地时间是否在有夏令时的时间段,也就是调整了夏令时。

对于夏季夏令时 +1 的“欧洲/柏林”:

  • 1 月 1 日 10:00 => 1 月 1 日 9:00 UTC
  • 7 月 1 日 10:00 => 7 月 1 日 8:00 UTC

对于没有夏令时的“非洲/拉各斯”:

  • 1 月 1 日 10:00 => 1 月 1 日 9:00 UTC
  • 7 月 1 日 10:00 => 7 月 1 日 9:00 UTC

最佳答案

使用 pytz ,特别是它的 localize method :

import pytz
import datetime as dt

def to_utc(localdt,tz):
timezone=pytz.timezone(tz)
utc=pytz.utc
return timezone.localize(localdt).astimezone(utc)

if __name__=='__main__':
for tz in ('Europe/Berlin','Africa/Lagos'):
for date in (dt.datetime(2011,1,1,10,0,0),
dt.datetime(2011,7,1,10,0,0),
):
print('{tz:15} {l} --> {u}'.format(
tz=tz,
l=date.strftime('%b %d %H:%M'),
u=to_utc(date,tz).strftime('%b %d %H:%M %Z')))

产量

Europe/Berlin   Jan 01 10:00 --> Jan 01 09:00 UTC
Europe/Berlin Jul 01 10:00 --> Jul 01 08:00 UTC
Africa/Lagos Jan 01 10:00 --> Jan 01 09:00 UTC
Africa/Lagos Jul 01 10:00 --> Jul 01 09:00 UTC

关于Python - 从 DST 调整的本地时间到 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6801429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com