在 tz 不知道时间、UTC 之间正确转换并在 python 中使用时区

发布于 2024-12-06 22:30:02 字数 1292 浏览 0 评论 0原文

我有一个格式为“20111014T090000”的字符串,带有关联的时区 ID (TZID=America/Los_Angeles),我想要 将其转换为具有适当偏移量的 UTC 时间(以秒为单位)。

问题似乎是我的输出时间缩短了 1 小时(它在 PST 中,而应该是 PDT),并且我正在使用 pytz 来帮助处理 timezo

import pytz

def convert_to_utc(date_time)
    # date_time set to '2011-10-14 09:00:00' and is initially unaware of timezone information

    timezone_id = 'America/Los_Angeles'
    tz = pytz.timezone(timezone_id);

    # attach the timezone
    date_time = date_time.replace(tzinfo=tz);

    print("replaced: %s" % date_time);                                                                          
    # this makes date_time to be: 2011-10-14 09:00:00-08:00
    # even though the offset should be -7 at the present time

    print("tzname: %s" % date_time.tzname());
    # tzname reports PST when it should be PDT

    print("timetz: %s" % date_time.timetz());
    # timetz: 09:00:00-08:00 - expecting offset -7

    date_time_ms = int(time.mktime(date_time.utctimetuple())); 
    # returns '1318611600' which is 
    # GMT: Fri, 14 Oct 2011 17:00:00 GMT
    # Local: Fri Oct 14 2011 10:00:00 GMT-7

    # when expecting: '1318608000' seconds, which is
    # GMT: Fri, 14 Oct 2011 16:00:00 GMT
    # Local: Fri Oct 14 2011 9:00:00 GMT-7 -- expected value

如何根据时区 ID 获得正确的偏移量?

I have a string in the form '20111014T090000' with associated timezone ID (TZID=America/Los_Angeles) and I want
to convert this to UTC time in seconds with the appropriate offset.

The problem seems to that my output time is off by 1 hour (it's in PST when it should be PDT) and I'm using the pytz to help with timezo

import pytz

def convert_to_utc(date_time)
    # date_time set to '2011-10-14 09:00:00' and is initially unaware of timezone information

    timezone_id = 'America/Los_Angeles'
    tz = pytz.timezone(timezone_id);

    # attach the timezone
    date_time = date_time.replace(tzinfo=tz);

    print("replaced: %s" % date_time);                                                                          
    # this makes date_time to be: 2011-10-14 09:00:00-08:00
    # even though the offset should be -7 at the present time

    print("tzname: %s" % date_time.tzname());
    # tzname reports PST when it should be PDT

    print("timetz: %s" % date_time.timetz());
    # timetz: 09:00:00-08:00 - expecting offset -7

    date_time_ms = int(time.mktime(date_time.utctimetuple())); 
    # returns '1318611600' which is 
    # GMT: Fri, 14 Oct 2011 17:00:00 GMT
    # Local: Fri Oct 14 2011 10:00:00 GMT-7

    # when expecting: '1318608000' seconds, which is
    # GMT: Fri, 14 Oct 2011 16:00:00 GMT
    # Local: Fri Oct 14 2011 9:00:00 GMT-7 -- expected value

How do I get the correct offset based on the timezone Id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

从此见与不见 2024-12-13 22:30:02

以下代码片段将执行您想要的操作。

def convert(dte, fromZone, toZone):
    fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone)
    return fromZone.localize(dte, is_dst=True).astimezone(toZone)

这里的关键部分是将 is_dst 传递给 localize 方法。

The following snippet will do what you wish

def convert(dte, fromZone, toZone):
    fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone)
    return fromZone.localize(dte, is_dst=True).astimezone(toZone)

The crucial part here is to pass is_dst to the localize method.

好倦 2024-12-13 22:30:02

simple-date 的编写就是为了使这样的转换变得简单(您需要 0.2.1 或更高版本才能进行转换)这):

>>> from simpledate import *
>>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp
1318608000.0

simple-date was written to make conversions like this trivial (you need version 0.2.1 or later for this):

>>> from simpledate import *
>>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp
1318608000.0
§普罗旺斯的薰衣草 2024-12-13 22:30:02

如果(暂时)允许更改程序中的全球时区,您还可以执行以下操作:

os.environ['TZ'] = 'America/Los_Angeles'
t = [2011, 10, 14, 9, 0, 0, 0, 0, -1]
return time.mktime(time.struct_time(t))

返回预期的 1318608000.0。

If changing the global time zone in your program is (temporarily) allowed, you can also do this:

os.environ['TZ'] = 'America/Los_Angeles'
t = [2011, 10, 14, 9, 0, 0, 0, 0, -1]
return time.mktime(time.struct_time(t))

The expected 1318608000.0 is returned.

过潦 2024-12-13 22:30:02

要将给定字符串转换为原始日期时间对象:

>>> from datetime import datetime
>>> naive_dt = datetime.strptime('20111014T090000', '%Y%m%dT%H%M%S')
>>> naive_dt
datetime.datetime(2011, 10, 14, 9, 0)

附加时区(使其成为感知日期时间对象):

>>> import pytz
>>> tz = pytz.timezone('America/Los_Angeles')
>>> local_dt = tz.localize(naive_dt, is_dst=None)
>>> print(local_dt.strftime("%Y-%m-%d %H:%M:%S %Z%z"))
2011-10-14 09:00:00 PDT-0700

注意:is_dst=None 用于引发不存在或不明确的本地时间的异常。

要从感知的日期时间对象获取 POSIX 时间戳:

>>> (local_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
1318608000.0

您问题中的主要问题是:

  1. 您替换 tzinfo 属性,应使用 tz.localize 代替
  2. mktime() 使用本地时间(您的计算机时区),而不是 UTC。

To convert given string to a naive datetime object:

>>> from datetime import datetime
>>> naive_dt = datetime.strptime('20111014T090000', '%Y%m%dT%H%M%S')
>>> naive_dt
datetime.datetime(2011, 10, 14, 9, 0)

To attach the timezone (make it an aware datetime object):

>>> import pytz
>>> tz = pytz.timezone('America/Los_Angeles')
>>> local_dt = tz.localize(naive_dt, is_dst=None)
>>> print(local_dt.strftime("%Y-%m-%d %H:%M:%S %Z%z"))
2011-10-14 09:00:00 PDT-0700

Note: is_dst=None is used to raise an exception for non-existing or ambiguous local times.

To get POSIX timestamp from an aware datetime object:

>>> (local_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
1318608000.0

The main issues in your question are:

  1. You replace tzinfo attribute, tz.localize should be used instead
  2. mktime() works with local time (your computer timezone), not UTC.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文