Search code examples
pythonpandasdatedatetimestrptime

How to convert dataframe column with datetime value to ISO-8601 time format with timezone?


How can I convert all dataframe column value to ISO-8601 format

Given below the sample value I get, when I execute print(df['timestamp']) for reference

0 2020-02-03 18:00:33
1 2020-02-03 18:00:37
2 2020-02-03 18:00:39
3 2020-02-03 18:01:16
4 2020-02-03 18:01:17
5 2020-02-03 18:02:14
6 2020-02-03 18:02:46
7 2020-02-03 18:02:50
8 2020-02-03 18:02:58

Given below the Expected Result

0 2020-02-03T18:00:33-06
1 2020-02-03T18:00:37-06
2 2020-02-03T18:00:39-06
3 2020-02-03T18:01:16-06
4 2020-02-03T18:01:17-06
5 2020-02-03T18:02:14-06
6 2020-02-03T18:02:46-06
7 2020-02-03T18:02:50-06
8 2020-02-03T18:02:58-06


Solution

  • df = pd.DataFrame()
    
    df['timestamp'] = pd.date_range('2018-01-01', periods=10, freq='H')
    

    If you just want to output in isoformat:

    df['timestamp'].map(lambda x: x.isoformat())
    

    If you want to create an extra column:

    df['iso_timestamp'] = df['timestamp'].map(lambda x: x.isoformat())
    

    If you want to overwrite:

    df['timestamp'] = df['timestamp'].map(lambda x: x.isoformat())