Python DST 与添加后时区检测

发布于 2024-12-05 18:21:35 字数 536 浏览 1 评论 0原文

所以我目前有一行代码,如下所示:

        t1 = datetime(self.year, self.month, self.day, self.hour, self.minute, self.second)
        ...
        t2 = timedelta(days=dayNum, hours=time2.hour, minutes=time2.minute, seconds=time2.second)
        sumVal = t1 + t2

我希望结果考虑到可能发生的任何 DST 影响(例如,如果我在 11/4/2012 00:30 AM 并添加 3 小时,由于夏令时有所回退,我会得到凌晨 02:30。我研究过使用 pytz 和 python-dateutil,它们似乎都不支持这一点,或者至少在没有包含所有时区的单独文件的情况下不支持它。更重要的是,这些时间不一定与当前系统位于同一时区,甚至不一定是过去的时区。我确信有一种简单的方法可以做到这一点(或者我希望 Python 能做到这一点),但现在似乎没有什么是我所需要的。有什么想法吗?

So I currently have a line of code which looks like this:

        t1 = datetime(self.year, self.month, self.day, self.hour, self.minute, self.second)
        ...
        t2 = timedelta(days=dayNum, hours=time2.hour, minutes=time2.minute, seconds=time2.second)
        sumVal = t1 + t2

I would like for the result to take into account any DST affects that might occur (such as if I am at 11/4/2012 00:30 AM and add 3 hours, I would get 02:30 AM, due to a fall back for DST). I've looked at using pytz and python-dateutil, and neither of them seem to support this, or at least not support it without a separate file which contains all of the time zones. The kicker is that the times may not necessarily be in the same time zone as the current system, or even be in the past. I'm sure there is a simple way to do this (or I would expect so out of Python), but nothing seems to be what I need right now. Any ideas?

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

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

发布评论

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

评论(1

静待花开 2024-12-12 18:21:35

也许 pytznormalize 方法就是您正在寻找的:

import datetime as dt
import pytz

tz=pytz.timezone('Europe/London')
t1 = dt.datetime(2012,10,28,0,30,0)
t1=tz.localize(t1)
t2 = dt.timedelta(hours=3)
sumVal = t1 + t2

sumVal 保留在 BST 中:

print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 3, 30, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

标准化后,sumVal采用 GMT:

sumVal = tz.normalize(sumVal)
print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 2, 30, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)

请注意,对于伦敦,DST 转换发生在 2012-10-28 02:00:00

Perhaps pytz's normalize method is what you are looking for:

import datetime as dt
import pytz

tz=pytz.timezone('Europe/London')
t1 = dt.datetime(2012,10,28,0,30,0)
t1=tz.localize(t1)
t2 = dt.timedelta(hours=3)
sumVal = t1 + t2

sumVal remains in BST:

print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 3, 30, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

After normalization, sumVal is in GMT:

sumVal = tz.normalize(sumVal)
print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 2, 30, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)

Note, for London, the DST transition occurs at 2012-10-28 02:00:00.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文