Converting datetime from one time zone to another using pytz

一笑奈何 提交于 2019-12-11 09:37:43

问题


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 Timezone
  2. EST Timezone

I want to translate those date/timestamps to Frankfurt time.

This involves using:

  1. CET Timezone
  2. CEST Timezone

Depending on the specific date.

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

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

How shall this conversion be done using pytz?


回答1:


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.

For example:

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


来源:https://stackoverflow.com/questions/54374804/converting-datetime-from-one-time-zone-to-another-using-pytz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!