Search code examples
pythonpandastimetimezone

How to convert a pandas datetime column from UTC to EST


There is another question that is eleven years old with a similar title.

I have a pandas dataframe with a column of datetime.time values.

val    time
a      12:30:01.323
b      12:48:04.583
c      14:38:29.162

I want to convert the time column from UTC to EST.

I tried to do dataframe.tz_localize('utc').tz_convert('US/Eastern') but it gave me the following error: RangeIndex Object has no attribute tz_localize


Solution

  • tz_localize and tz_convert work on the index of the DataFrame. So you can do the following:

    1. convert the "time" to Timestamp format
    2. set the "time" column as index and use the conversion functions
    3. reset_index()
    4. keep only the time

    Try:

    dataframe["time"] = pd.to_datetime(dataframe["time"],format="%H:%M:%S.%f")
    output = (dataframe.set_index("time")
                       .tz_localize("utc")
                       .tz_convert("US/Eastern")
                       .reset_index()
              )
    output["time"] = output["time"].dt.time
    
    >>> output
                  time val
    0  15:13:12.349211   a
    1  15:13:13.435233   b
    2  15:13:14.345233   c