我想知道某一天的开始和结束时间在 UTC 和 Python 中的表达方式。
例如:
现在我想获得这些 UTC 时间:
我不想以编程方式设置时区 - 我想从我的系统中获取它。
我发现这在 Swift 中很容易做到,因为每个日期都是时区感知的,但我不知道如何在 Python 中做到这一点。我需要这样做的原因是因为我想从数据库中获取特定(本地)日期内的所有数据,其中包含 UTC 时间戳。
我试过这个:
from datetime import datetime, time
import pytz
start_of_day = datetime.combine(datetime.now(), time.min)
end_of_day = datetime.combine(datetime.now(), time.max)
print(start_of_day)
print(end_of_day)
print(start_of_day.astimezone().tzinfo)
print(end_of_day.astimezone().tzinfo)
start_of_day = pytz.utc.localize(start_of_day)
end_of_day = pytz.utc.localize(end_of_day)
print(start_of_day)
print(end_of_day)
print(start_of_day.astimezone().tzinfo)
print(end_of_day.astimezone().tzinfo)
给出以下输出:
2023-10-29 00:00:00
2023-10-29 23:59:59.999999
BST
GMT
2023-10-29 00:00:00+00:00
2023-10-29 23:59:59.999999+00:00
BST
GMT
虽然我期望,类似(我猜 UTC 也可能是 GMT):
2023-10-29 00:00:00
2023-10-29 23:59:59.999999
CEST
CET
2023-10-28 22:00:00+00:00
2023-10-29 22:59:59.999999+00:00
UTC
UTC
不仅时间不对,时区也很奇怪。
pytz 的
localize
只是设置时区,它不会像 astimezone
那样进行转换。
这是代码的稍微修改版本。我们可以使用标准 lib datetime.timezone.utc 来设置 UTC,让事情变得更清晰(顺便说一句,自 Python 3.9 起,pytz 已被弃用)。另请参阅代码中的注释以获取一些解释。
from datetime import datetime, time, timezone
start_of_day = datetime.combine(datetime.now(), time.min)
end_of_day = datetime.combine(datetime.now(), time.max)
print(start_of_day) # naive datetime here...
print(end_of_day)
print(start_of_day.astimezone().tzinfo)
print(end_of_day.astimezone().tzinfo)
start_of_day = start_of_day.astimezone(timezone.utc) # convert / make aware, UTC
end_of_day = end_of_day.astimezone(timezone.utc)
print(start_of_day)
print(end_of_day)
print(start_of_day.tzinfo) # datetime object is already aware here, no need for astimezone
print(end_of_day.tzinfo)
在配置为使用时区“欧洲/柏林”的我的系统上,输出为
2023-10-29 00:00:00 # naive datetime, but "silently" on UTC+2
2023-10-29 23:59:59.999999 # same but UTC+1
CEST
CET
# Note that the conversion from local to UTC applies the UTC offset:
2023-10-28 22:00:00+00:00 # was on UTC+2, so clock moves back 2h for UTC
2023-10-29 22:59:59.999999+00:00 # was UTC+1, clock back 1h
UTC
UTC