from datetime import datetime, timezone, timedelta
import pytz
t11 = datetime(1918, 4, 15, 0, 0, tzinfo=timezone.utc).astimezone(pytz.timezone('Europe/Berlin'))
t12 = t11 + timedelta(hours=1)
t2 = datetime(1918, 4, 15, 1, 0, tzinfo=timezone.utc).astimezone(pytz.timezone('Europe/Berlin'))
print(t12)
print(t2)
1918-04-15 02:00:00+01:00
1918-04-15 03:00:00+02:00
我希望这两者都是我对t2
的看法。关键区别在于t2.hour
与t12.hour
。对于时区感知的日期时间对象,我希望小时是本地小时。
如何更改此行为?这样的原因是什么原因?
答案 0 :(得分:-1)
我不接受以下内容,因为它只解释了如何正确行事。它没有解释为什么首先添加timedelta不能以预期的方式工作。
StackActions
建议采取以下方法:
from datetime import datetime, timezone, timedelta
import pytz
# Timezone-aware object to start with
t11 = datetime(1918, 4, 15, 0, 0, tzinfo=timezone.utc).astimezone(pytz.timezone('Europe/Berlin'))
# Extract timezone information
tzinfo = t11.tzinfo
# Convert to UTC, add timedelta, convert to local timezone
t13 = (t11.astimezone(pytz.timezone('utc')) + timedelta(hours=1)).astimezone(tzinfo)
另一种方法:
t14 = t11 + timedelta(hours=1) # Invalid timezone!
t14 = t14.astimezone(pytz.utc).astimezone(t14.tzinfo) # Fix the timezone
现在我有:
t11: 1918-04-15 01:00:00+01:00
t13: 1918-04-15 03:00:00+02:00 # one hour more and +1h because of DST
包This answer是另一种解决方法:
from pendulum import datetime
from datetime import timedelta
import pytz
t11 = datetime(1918, 4, 15, 0, 0).astimezone(pytz.timezone('Europe/Berlin'))
t12 = t11 + timedelta(hours=1)
t2 = datetime(1918, 4, 15, 1, 0).astimezone(pytz.timezone('Europe/Berlin'))
给出:
t11: 1918-04-15T01:00:00+01:00
t12: 1918-04-15T03:00:00+02:00
t2 : 1918-04-15T03:00:00+02:00