'Europe/Madrid' 时区不匹配 'Etc/GMT+1'

'Europe/Madrid' timezone doesn't match 'Etc/GMT+1'

我正在尝试将 UTC 时间戳转换为西班牙时区的时间戳。

>>> import datetime as dt
>>> import pytz
>>> today = dt.datetime.utcfromtimestamp(1573516800)
datetime.datetime(2019, 11, 12, 0, 0)

>>> today.replace(tzinfo=pytz.timezone('Europe/Madrid')).timestamp()
1573517700.0

>>> today.replace(tzinfo=pytz.timezone('Etc/GMT+1')).timestamp()
1573520400.0

令我惊讶的是 Europe/MadridEtc/GMT+1 得到了不同的结果。为什么是这样? Europe/Madrid 应该以不同的方式使用,还是可能是错误?

UTC 时间戳:UTC 时间自 1970 年 1 月 1 日以来的秒数。

Python 日期时间:查看时间的好方法,对用户友好

UTC 时间戳不受时区影响,但日期时间受时区影响。

此代码采用给定时间戳并将其转换为 UTC 日期时间和 Europe/Madrid 时区。

import datetime as dt
import pytz

# define the old and new timezones
old_timezone = pytz.timezone("UTC")
new_timezone = pytz.timezone("Europe/Madrid")

# get an 'offset-aware' datetime
today = dt.datetime.utcfromtimestamp(1573516800)
my_datetime = old_timezone.localize(today)

# returns datetime in the new timezone
my_datetime_in_new_timezone = my_datetime.astimezone(new_timezone)

print("Old:", str(my_datetime), "\nNew:", str(my_datetime_in_new_timezone), "\nDifference:",
      str(my_datetime - my_datetime_in_new_timezone))

输出:

Old: 2019-11-12 00:00:00+00:00 
New: 2019-11-12 01:00:00+01:00 
Difference: 0:00:00

代码改编自:

几件事:

  • Europe/Madrid 在标准时间是 UTC+1,在夏令时(又名夏令时)是 UTC+2。

  • Etc/GMT+1 是全年的 UTC-1。请注意,该标志与您的预期相反。见tzdata sources, and on Wikipedia.

  • 中的解释
  • 由于马德里在您提供的日期使用 UTC+1,因此如果您使用 Etc/GMT-1,您会得到与该日期相同的结果。但是,我不建议这样做,因为您稍后会得到错误的夏令时约会结果。

  • Etc/GMT±X 区域主要用于不可定位的场景,例如跟踪海上船上的时间 - 不适用于陆地上的人口稠​​密地点。

  • showed, you should be using the localize function rather than replace to assign a time zone. This is covered in the pytz documentation.