Mainland
Mainland

Reputation: 4584

Python Convert Daylight Saving time to Standard Zone time

I have data coming from field (Florida), which saves it in local time. Florida has day light saving time. So, I want to convert this to EST zone. How do I do it? My code:

local_df.index = DatetimeIndex(['2019-06-01 06:58:45', '2019-10-01 06:59:00',
               '2019-10-01 06:59:15', 
               '2020-07-18 09:16:30', '2020-07-18 09:16:45'],
              dtype='datetime64[ns]', name='', freq=None)
est_df.index = local_df.index.tz_localize(tz='EST')
est_df.index = DatetimeIndex(['2019-06-01 06:58:45-05:00', '2019-10-01 06:59:00-05:00',
               '2019-10-01 06:59:15-05:00','2020-07-18 09:16:30-05:00', '2020-07-18 09:16:45-05:00'],
              dtype='datetime64[ns]', name='', freq=None)

My above code is actually not converting local time to the eastern standard time, it appends only the time difference with UCT. This is not correct.

Upvotes: 0

Views: 285

Answers (1)

FObersteiner
FObersteiner

Reputation: 25634

Note that EST is not a time zone but an offset from UTC of certain time zone(s) at a certain time of the year. I suggest to use IANA time zone names instead for an unambiguous geographical attribution. Side note: Florida has two time zones; US/Eastern and US/Central.

Furthermore, to convert UTC time to a time zone's time, you'll have to localize to UTC first. Your code could look something like

import pandas as pd

dti = pd.DatetimeIndex(['2019-06-01 06:58:45', '2019-10-01 06:59:00', '2019-10-01 06:59:15', 
                        '2020-07-18 09:16:30', '2020-07-18 09:16:45'])

dti_UTC = dti.tz_localize('UTC')
dti_USEastern = dti_UTC.tz_convert('US/Eastern')

# dti_USEastern
# DatetimeIndex(['2019-06-01 02:58:45-04:00', '2019-10-01 02:59:00-04:00',
#                '2019-10-01 02:59:15-04:00', '2020-07-18 05:16:30-04:00',
#                '2020-07-18 05:16:45-04:00'],
#               dtype='datetime64[ns, US/Eastern]', freq=None)

If, however, the input resembles local time, say US/Eastern, you can directly localize to that time zone:

dti_USEastern = dti.tz_localize('US/Eastern')

# dti_USEastern
# DatetimeIndex(['2019-06-01 06:58:45-04:00', '2019-10-01 06:59:00-04:00',
#                '2019-10-01 06:59:15-04:00', '2020-07-18 09:16:30-04:00',
#                '2020-07-18 09:16:45-04:00'],
#               dtype='datetime64[ns, US/Eastern]', freq=None)

Upvotes: 1

Related Questions