UTC 本地开始和结束时间

问题描述 投票:0回答:1

我想知道某一天的开始和结束时间在 UTC 和 Python 中的表达方式。

例如:

  • 当前日期和时间是 2023 年 10 月 29 日星期日 01:33:49 CEST(中欧夏令时间),
  • 这一天从 2023 年 10 月 29 日星期日, 00:00:00 CEST 开始,
  • 这一天于 2023 年 10 月 29 日星期日 23:59:59 CET 结束(注意,时区从 CEST(夏令时)切换到 CET(不在夏令时)

现在我想获得这些 UTC 时间:

  • 开始:2023 年 10 月 28 日星期六,22:00:00 UTC
  • 结束:UTC 时间 2023 年 10 月 29 日星期日 22:59:59(一天包含 25 小时)

我不想以编程方式设置时区 - 我想从我的系统中获取它。

我发现这在 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

不仅时间不对,时区也很奇怪。

python datetime timezone python-datetime pytz
1个回答
0
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.