Python 似乎无法正确处理时区转换
Python seeming to incorrectly handle time zone conversions
我对我编写的用于转换日期和时间的 python 程序中的以下行为感到困惑。我有新西兰标准时间原始“挂钟时间”中的数据,并希望将其转换为始终为 UTC+12(或 pytz 中提供的 GMT+12)。
问题是当我 运行 程序给出的结果似乎不正确。示例输出如下所示。当输入 24/07/2015 08:00 小时(2015 年 7 月 24 日上午 8 点)的日期时,定义为 'Pacific/Auckland',然后转换为 GMT+12,它似乎给出了一天前的错误结果.我不确定这是为什么,因为如果我对时区转换的理解是正确的,时间应该完全相同。
有人能指出我做错了什么吗?
程序输出:
Pacific/Auckland
24/07/2015 08:00
23/07/2015 08:00
“最小工作示例”源代码:
#!/usr/bin/env python
import time
import pytz
import datetime
def main():
time_zone = 'Pacific/Auckland'
print(time_zone)
local = pytz.timezone(time_zone)
time_str = '24/07/2015 08:00'
print(time_str)
t = time.strptime(time_str, '%d/%m/%Y %H:%M')
t_datetime = datetime.datetime.fromtimestamp(time.mktime(t))
local_dt = local.localize(t_datetime)
ds2 = local_dt.astimezone(pytz.timezone('Etc/GMT+12')).strftime('%d/%m/%Y %H:%M')
print(ds2)
if __name__ == '__main__':
# Parse the system arguments and get the busbar and input directory.
main()
##### END OF FILE #####
POSIX style timezones ('Etc/GMT+h') have the opposite sign。您正在从 +1200
转换为 -1200
,总共休息 24 小时,这就是为什么您得到相同的时间但错误的日期。
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
naive = datetime.strptime('24/07/2015 08:00', '%d/%m/%Y %H:%M')
aware = pytz.timezone('Pacific/Auckland').localize(naive, is_dst=None)
print(aware)
utc_dt = aware.astimezone(pytz.utc)
print(utc_dt)
# +1200
print(utc_dt.astimezone(pytz.timezone('Etc/GMT-12')))
输出
2015-07-24 08:00:00+12:00
2015-07-23 20:00:00+00:00
2015-07-24 08:00:00+12:00
我对我编写的用于转换日期和时间的 python 程序中的以下行为感到困惑。我有新西兰标准时间原始“挂钟时间”中的数据,并希望将其转换为始终为 UTC+12(或 pytz 中提供的 GMT+12)。
问题是当我 运行 程序给出的结果似乎不正确。示例输出如下所示。当输入 24/07/2015 08:00 小时(2015 年 7 月 24 日上午 8 点)的日期时,定义为 'Pacific/Auckland',然后转换为 GMT+12,它似乎给出了一天前的错误结果.我不确定这是为什么,因为如果我对时区转换的理解是正确的,时间应该完全相同。
有人能指出我做错了什么吗?
程序输出:
Pacific/Auckland
24/07/2015 08:00
23/07/2015 08:00
“最小工作示例”源代码:
#!/usr/bin/env python
import time
import pytz
import datetime
def main():
time_zone = 'Pacific/Auckland'
print(time_zone)
local = pytz.timezone(time_zone)
time_str = '24/07/2015 08:00'
print(time_str)
t = time.strptime(time_str, '%d/%m/%Y %H:%M')
t_datetime = datetime.datetime.fromtimestamp(time.mktime(t))
local_dt = local.localize(t_datetime)
ds2 = local_dt.astimezone(pytz.timezone('Etc/GMT+12')).strftime('%d/%m/%Y %H:%M')
print(ds2)
if __name__ == '__main__':
# Parse the system arguments and get the busbar and input directory.
main()
##### END OF FILE #####
POSIX style timezones ('Etc/GMT+h') have the opposite sign。您正在从 +1200
转换为 -1200
,总共休息 24 小时,这就是为什么您得到相同的时间但错误的日期。
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
naive = datetime.strptime('24/07/2015 08:00', '%d/%m/%Y %H:%M')
aware = pytz.timezone('Pacific/Auckland').localize(naive, is_dst=None)
print(aware)
utc_dt = aware.astimezone(pytz.utc)
print(utc_dt)
# +1200
print(utc_dt.astimezone(pytz.timezone('Etc/GMT-12')))
输出
2015-07-24 08:00:00+12:00
2015-07-23 20:00:00+00:00
2015-07-24 08:00:00+12:00