Python - 从调整夏令时的当地时间到UTC

8 投票
2 回答
3376 浏览
提问于 2025-04-16 22:08

有一家特定的银行在全球所有主要城市都有分支机构。它们都在当地时间早上10点开门。如果在使用夏令时的时区,那么当地的开门时间也会根据夏令时进行调整。那么,如何把当地时间转换成协调世界时(UTC)呢?

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

参数:

  • localdt:当地时间,作为一个简单的日期时间对象,已经调整了夏令时
  • tz:时区,采用TZ格式,比如 'Europe/Berlin'

返回值:

  • 一个日期时间对象,表示UTC时间,并且是时区感知的

编辑:

最大的挑战是判断当地时间是否在夏令时期间,这也意味着它已经根据夏令时进行了调整。

以 'Europe/Berlin' 为例,夏天有+1小时的夏令时:

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

而 'Africa/Lagos' 则没有夏令时:

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

2 个回答

1
from datetime import datetime, tzinfo, timedelta

class GMT1(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=1)
    def dst(self, dt):
        return timedelta(0)
    def tzname(self,dt):
        return "Europe/Prague"
year, month, day = 2011, 7, 23
dt = datetime(year, month, day, 10)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return timedelta(0)
    def dst(self, dt):
        return timedelta(0)
    def tzname(self,dt):
        return "UTC"

def utc(localt, tz):
    return localt.replace(tzinfo=tz).astimezone(UTC())

print utc(dt, GMT1())

新版本。这段代码可以满足你的需求——它接收一个简单的日期时间和一个时区,然后返回一个UTC(协调世界时)格式的日期时间。

9

使用 pytz 库,特别是它的 localize 方法

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

撰写回答