如何添加每周timedeltas关于夏令时区 [英] How to add weekly timedeltas with regards to daylight saving timezones
问题描述
我想对本地化的datetime对象添加或减去周(或几天或几个月或几年)。问题是,天真的方法将导致夏令时间区内的1小时班次。
I want to add or subtract weeks (or days or month or years) to localized datetime objects. The problem is, that the naive approach will result in 1 hour shifts due to daylight saving timezones.
2014-03-27 12:00从冬天开始之前到夏天如果我在这个时间段内添加一周的timedelta本地化在例如时区欧洲/柏林,结果将是2014-04-03 13:00。我想要有同样的时间,2014-04-03 12:00。我找到一个解决方案:
2014-03-27 12:00 is right before the switch from winter to summer time. If I add a timedelta of one week to this date localized in timezone Europe/Berlin for example, the result will be 2014-04-03 13:00. I would like to have the same hour of day, 2014-04-03 12:00. I found a solution:
from datetime import datetime, timedelta
import pytz
my_tz = pytz.timezone("Europe/Berlin")
def add_relativedelta(date, delta):
"""
Adds the given timedelta to the given date. Shifts in timezone offsets
will be removed.
"""
tz = date.tzinfo
result = tz.normalize(date + delta)
if result.utcoffset() != date.utcoffset():
result = tz.normalize(date.utcoffset() - result.utcoffset() + result)
return result
date = my_tz.localize(datetime(year=2014, month=3, day=27, hour=12, minute=0))
print """{} Original localized date (winter time)
{} One week later (summer time)
{} Date one week later preserving hour of day (summer time)""".format(date,
my_tz.normalize(date + timedelta(days=7)),
add_relativedelta(date, timedelta(days=7)))
2014-03-27 12:00:00+01:00 Original localized date (winter time)
2014-04-03 13:00:00+02:00 One week later (summer time)
2014-04-03 12:00:00+02:00 Date one week later preserving hour of day (summer time)
我想知道是否有更多的通用/更好的解决方案。有什么图书馆可以解决这个问题吗?这似乎是一个很常见的问题。
I was wondering if there is more generic/better solution. Are there any libraries that could solve this? This seems to be a pretty common issue.
推荐答案
timedelta(days = 7)
表示7天,如 7 * 24
小时 - 不是太阳日。
如果您将时区添加7天添加到时区,您将获得7天之后的日期时间,而不管时区中的日期时间表示 。
timedelta(days=7)
means 7 days, as in 7*24
hours - not "solar days".
If you add 7 days to a timezone-aware datetime, you'll obtain a datetime that is 7 days later - independently of how that datetime is represented in the timezone.
似乎您真正想要的是将delta增加到您指定的时间,忽略时区详细信息。注意区别:
It seems what you really want is to apply the delta to the time you specified, ignoring timezone details. Notice the difference:
In [13]: print my_tz.normalize( my_tz.localize( dt ) + delta )
2014-04-03 13:00:00+02:00
In [14]: print my_tz.normalize( my_tz.localize( dt + delta ) )
2014-04-03 12:00:00+02:00
所以,如果可能,将三角形应用到数据时间在他们本地化之前。
So, if possible, apply the deltas to the datetimes before they are localized.
这篇关于如何添加每周timedeltas关于夏令时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!