如果我将UTC时间增加1小时并进行本地化,或者将本地时间增加1小时,为什么会有所不同? [英] Why does it make a difference if I add 1 hour to the UTC time and localize or 1 hour to the local time?
问题描述
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)
已观察
Observed
1918-04-15 02:00:00+01:00
1918-04-15 03:00:00+02:00
期望
我期望两者都是我所看到的 t2
。关键的区别是 t2.hour
与 t12.hour
。对于可识别时区的datetime对象,我希望小时为本地小时。
Expected
I expected both to be what I see for t2
. The crucial difference is t2.hour
vs t12.hour
. For a timezone-aware datetime object, I expected the hour to be the local hour.
如何更改此行为?这样的原因是什么?
How can I change this behaviour? What is the reason for having it like this?
推荐答案
我将不接受以下内容,因为它仅说明了操作方法对。它并不能解释为什么添加timedelta在一开始就无法按预期方式工作。
I will not accept the following, because it only explains how to do it right. It doesn't explain why adding timedelta doesn't work the expected way in the first place.
此答案建议采用以下方法:
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
多一小时又+ 1h
摆锤
包 摆锤
是另一种解决方法:
Pendulum
The package pendulum
is another way to fix it:
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
这篇关于如果我将UTC时间增加1小时并进行本地化,或者将本地时间增加1小时,为什么会有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!