Search code examples
pythonpandasdataframetimestamputc

Converting Timestamp to UTC pandas


I have a pandas dataframe in the below format. The Timestamp values are in DateTime format (GMT Time) I want to add a new column to the dataframe with the UTC values related to each Timestamp.

How can I do this in pandas?

df = pd.DataFrame({'ID': ['1', '2', '3'],
                     'TimeStamp': [2022-12-19 22:56:24, 2022-12-19 22:57:46, 2022-12-19 22:59:08]})

I tried the below code, but it gives me an error.

df['x'] = dt.datetime(df['TimeStamp']).timestamp()

TypeError: cannot convert the series to <class 'int'>

Desired Output:

ID TimeStamp UTC
1 2022-12-19 22:56:24 1671490584
2 2022-12-19 22:57:46 1671490666
3 2022-12-19 22:59:08 1671490748

Solution

  • One way:

    df["UTC"] = pd.to_datetime(df["TimeStamp"]).map(pd.Timestamp.timestamp).astype(int)
    print(df)
    
      ID           TimeStamp         UTC
    0  1 2022-12-19 22:56:24  1671490584
    1  2 2022-12-19 22:57:46  1671490666
    2  3 2022-12-19 22:59:08  1671490748