[英]Comparing two timezone-aware datetimes
Most probably, this question is asked hundred times, but I couldn't still find the answer.很可能,这个问题被问了一百次,但我仍然找不到答案。 I have the following code:
我有以下代码:
import pytz
import datetime
from pytz import timezone
tz_moscow = timezone('Europe/Moscow')
tz_yerevan = timezone('Asia/Yerevan')
dt1 = tz_yerevan.localize(datetime.datetime(2011, 7, 20, 0, 0, 0, 0))
dt2 = tz_moscow.localize(datetime.datetime(2011, 6, 20, 0, 0, 0, 0))
print (dt2.utcoffset()) # Expected 3, actual result - 4
print (dt1)
print (dt2)
print (dt1 == dt2)
I have two questions:我有两个问题:
dt1 < dt2
dt1 < dt2
来比较两个时区感知日期时间吗As you can see in these tests timezone aware datetime
can be compared.正如您在这些测试中看到的,可以比较时区感知
datetime
时间。 They will be compared with their timezone offset.他们将与他们的时区偏移量进行比较。
import datetime
from pytz import timezone
tz_moscow = timezone('Europe/Moscow')
tz_yerevan = timezone('Asia/Yerevan')
standard_datetime_object = datetime.datetime(2022, 1, 18, 0, 0, 0, 0)
moscow_datetime_object = tz_moscow.localize(standard_datetime_object)
yerevan_datetime_object = tz_yerevan.localize(standard_datetime_object)
yerevan_datetime_object_1h = tz_yerevan.localize(datetime.datetime(2022, 1, 18, 1, 0, 0, 0))
print(f"datetime object without UTC offset:\n{standard_datetime_object}\n")
print(f"datetime object with UTC offset +3:\n{moscow_datetime_object}\n")
print(f"datetime object with UTC offset +4:\n{yerevan_datetime_object}\n")
print(f"is same time with +3 greater than one with +4:\n{moscow_datetime_object > yerevan_datetime_object}\n")
print(f"is same time with +3 less than one with +4:\n{moscow_datetime_object < yerevan_datetime_object}\n")
print(f"is one o'clock in yerevan equal to midnight in moscow:\n{yerevan_datetime_object_1h == moscow_datetime_object}")
And the timezone offset is different during winter and summer so in july it is +4 wheras now (in january) it is +3.冬季和夏季的时区偏移量不同,因此在 7 月为 +4,而现在(1 月)为 +3。 (same goes for yerevan)
(埃里温也一样)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.