我无法理解 Python 中的 Unix 时间戳和时区转换。我有一个 UTC 日期时间字符串('2023-09-20T05:04:54')和纬度/经度坐标(多伦多周围)。我需要将此 UTC 时间转换为本地时间并获取两者的 Unix 时间戳,预计 UTC 和多伦多时间之间有 4 小时的时差。但是,两个时间戳看起来相同。
# The input time and lat/lon
utc = '2023-09-20T05:04:54'
latitude = 43.477361
longitude = -80.513589
# Find the time zone according to lat/lon
tf = TimezoneFinder()
local_timezone = tf.timezone_at(lng=longitude, lat=latitude)
local_timezone = ZoneInfo(local_timezone) # Convert string to timezone object
# Make sure the input time (utc) is recognized as UTC time by Python
utc_time = datetime.strptime(utc, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
# Convert to local time ('America/Toronto')
local_time = utc_time.replace(tzinfo=timezone.utc).astimezone(local_timezone)
# Print Unix timestamps
local_time.timestamp()
#Out[158]: 1695186294.0
utc_time.timestamp()
#Out[159]: 1695186294.0
UTC 与多伦多时区之间的时间偏移应为-4 小时。但是,UTC 时间和多伦多时间的 Unix 时间戳是相同的。有人可以解释一下为什么时间戳没有 4 小时的差异吗?
datetime.timestamp()
方法返回unix时间戳。 unix 时间戳是自 1970 年 1 月 1 日UTC以来的秒数。因此,无论时区如何,它总是返回相同的时间,因为它们距离 1970 年 1 月 1 日的“纪元时间”UTC 的秒数相同