Home > OS >  How to convert list of timestamp columns in Python Pandas with Time zone offset 1) Convert to UTC 2)
How to convert list of timestamp columns in Python Pandas with Time zone offset 1) Convert to UTC 2)

Time:10-03

How to convert list of timestamp columns in Python Pandas with Time zone offset

  1. Convert to UTC value without TZ offset
  2. Convert to EST value without TZ offset
  3. Just Remove TZ offset & store as is

I have list of four columns in a Pandas Data frame which has Timestamp with Time zone offset as follows: ts_lst = [SLA_START_TIME, SLA_STOP_TIME, RES_START_TIME, RES_STOP_TIME] Sample value : 2017-06-27T09:30:19.757-0400

For each of the columns in the ts_lst what is the optimal solution to

  1. Convert UTC Time zone to EST
  2. Remove the Time zone offset

CodePudding user response:

This should work:

for column in [x for x in df.columns[df.columns.str.contains("time", case=False)]]:
    df[column] = (
        pd.to_datetime(df[column], utc=True)
        .dt.tz_convert("America/New_York")
        .dt.tz_localize(None)
        .dt.floor("S")
    )
  • Related