Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting datetime from one time zone to another using pytz

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?

like image 655
M.E. Avatar asked Jun 08 '26 21:06

M.E.


1 Answers

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
like image 61
benvc Avatar answered Jun 10 '26 10:06

benvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!