使用pytz将datetime从一个时区转换为另一个时区 [英] Converting datetime from one time zone to another using pytz

查看:210
本文介绍了使用pytz将datetime从一个时区转换为另一个时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中包含来自纽约的日期/时间戳,没有时区信息。不会记录EDT或EST。

I have a data set which includes date/timestamps from New York WITHOUT timezone information. EDT or EST are not recorded.

日期包含几年的每日数据,因此同时包含这两个数据:

Dates include daily data for several years, so it includes both:


  1. EDT时区

  2. EST时区

我想翻译那些

这涉及使用:


  1. CET时区

  2. CEST时区

取决于特定日期。

我已经看到,在纽约时间,pytz包含 timezone('US / Eastern'),如果我正确理解,则包括两个时区(< a href = https://www.timeanddate.com/time/zone/usa/new-york-state rel = nofollow noreferrer>纽约时区)。

I have seen that for the NY time, pytz includes timezone('US/Eastern'), which if I understood correctly includes both timezones (New York Timezones).

对于法兰克福而言,您似乎需要明确指定CET或CEST
法兰克福时区)。

For Frankfurt, it seems that you need to explicitly specify CET or CEST (Frankfurt Timezones).

如何使用pytz进行此转换?

How shall this conversion be done using pytz?

推荐答案

您可以使用 localize()在纽约时间中创建您朴素的datetime对象,并在 astimezone()中创建它们,然后将其转换为法兰克福(柏林)时间。使用时区名称(而不是仅在一年的一部分期间使用的特定时区缩写)将为您处理夏令时差异。

You can convert from New York time to Frankfurt time by using localize() to create your naive datetime objects in New York time and astimezone() to then convert them to Frankfurt (Berlin) time. Using the timezone name (rather than a specific timezone abbreviation that only applies during part of the year) will handle the daylight savings difference for you.

例如:

from datetime import datetime
from pytz import timezone

newyork_tz = timezone('America/New_York')
berlin_tz = timezone('Europe/Berlin')

newyork = newyork_tz.localize(datetime(2018, 5, 1, 8, 0, 0))
berlin = newyork.astimezone(berlin_tz)
print(newyork)
print(berlin)
# OUTPUT
# 2018-05-01 08:00:00-04:00
# 2018-05-01 14:00:00+02:00

这篇关于使用pytz将datetime从一个时区转换为另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆