I have got a dataframe like this:
dt | value 2019-01-01 00:00:00 +0000 UTC | 49.0 2019-01-01 01:00:00 +0000 UTC | 39.8 2019-01-01 02:00:00 +0000 UTC | 23.4 2019-01-01 03:00:00 +0000 UTC | 45.3 This timestamp is in UTC timezone, but I would like to convert it to EST. Here was my attempt:
dtobj = pd.to_datetime(data['dt'], format='%Y-%m-%d %H:%M:%S +0000 %Z') dtobj = dtobj.replace(tzinfo=ZoneInfo('US/Eastern')) but it has the following error:
TypeError: replace() got an unexpected keyword argument 'tzinfo'
I didn't find a clear answer to explain why this error happened. Are there any other ways to convert the timezone?
12 Answers
Try using dt.tz_convert:
>>> df['dt'] = pd.to_datetime(df['dt'], format='%Y-%m-%d %H:%M:%S +0000 %Z') >>> df['dt'] = df['dt'].dt.tz_convert('US/Eastern') >>> df dt value 0 2018-12-31 19:00:00-05:00 49.0 1 2018-12-31 20:00:00-05:00 39.8 2 2018-12-31 21:00:00-05:00 23.4 3 2018-12-31 22:00:00-05:00 45.3 >>> 3You'll need to use the pytz module (available from PyPI):
import pytz from datetime import datetime est = pytz.timezone('US/Eastern') utc = pytz.utc fmt = '%Y-%m-%d %H:%M:%S %Z%z' dateTimeUtc= datetime(2016, 1, 24, 18, 0, 0, tzinfo=utc) dateTimeUtc.astimezone(est).strftime(fmt)