【发布时间】:2021-02-05 14:21:08
【问题描述】:
好的,在 Python 中从来没有像日期时间这样困难的东西。我有时间,my_time,这个时间总是需要在夏季增加 2 小时,在冬季增加 1 小时。 my_time 的正确时区是 EET。现在我试图将它与start_time 和end_time 进行比较,但我可以看到它在执行 if 语句时仍在寻找“基础”my_time。这怎么可能?
这是我的代码:
my_time = '20200907-07u00m00s'
my_time = datetime.datetime.strptime(my_time, '%Y%m%d-%Hu%Mm%Ss')
timezone= 'Europe/Amsterdam'
my_time = pytz.utc.localize(my_time).astimezone(pytz.timezone(timezone))
start_time = '202097060000'
start_time = datetime.datetime.strptime(start_time, '%Y%m%d%H%M%S')
start_time = pytz.utc.localize(start_time)
end_time = '202097080000'
end_time = datetime.datetime.strptime(end_time, '%Y%m%d%H%M%S')
end_time = pytz.utc.localize(end_time)
if my_time >= start_time and my_time <= end_time:
print('my_time IS between the start and end time')
else:
print('my_time IS NOT between the start and end time')
接收到的输出:
my_time IS between the start and end time
我猜代码正在检查 2020-09-07 07:00:00 是否介于 2020-09-07 06:00:00 和 2020-09-07 08:00:00....
我的预期输出是代码检查是否:
2020-09-07 09:00:00 介于 2020-09-07 06:00:00 和 2020-09-07 08:00:00 之间,这意味着它应该打印 my_time IS NOT between the start and end time
【问题讨论】:
-
start_time 和 end_time 都是 UTC,而 my_time 是本地时间 (UTC+2)。比较考虑了 UTC 偏移量,因此
2020-09-07 09:00:00+02:00介于2020-09-07 06:00:00+00:00和2020-09-07 08:00:00+00:00之间。 -
@MrFuppes 是的,我知道,这也是我在问题中所说的,但我希望
my_time成为2020-09-07 09:00:00而不是2020-09-07 09:00:00+02:00 -
那么你不应该本地化到时区,而是 UTC(就像你对开始和结束时间所做的那样)。
标签: python datetime timezone pytz