Search code examples
arrayspython-3.xdate-formattingmulti-indexpython-datetime

python multiindex array datetime formatting (as two different datetimes)


I have the following data:

     level_0   level_1   level_2
0    90936.0   91908.0  Profile1  
1    92551.0   93049.0      Run1
2    93459.0   94053.0  Profile2
3    94723.0   95333.0  Profile3
4    95444.0   95713.0      Run2
5   100221.0  100758.0      Run3
6   100937.0  101243.0      Run4

I would like to format the columns level_0 and level_1 as the times at which the observations were initiated (level_0) and ended(level_1):

     level_0   level_1   level_2
0    9:09:36   9:19:08  Profile1  
1    9:25:51   9:30:49      Run1
2    9:34:59   9:40:53  Profile2
3    9:47:23   9:53:33  Profile3
4    9:54:44   9:57:13      Run2
5   10:02:21  10:07:58      Run3

How can I do that ? Thanks


Solution

  • I'm assuming your dataframe is in pandas. In this case, one way is to use apply to apply pd.to_datetime to both columns, then use dt.time to access just the time string:

    df[['level_0','level_1']] = df[['level_0','level_1']].apply(lambda x: pd.to_datetime(x, format='%H%M%S.0').dt.time)
    >>> df
        level_0   level_1   level_2
    0  09:09:36  09:19:08  Profile1
    1  09:25:51  09:30:49      Run1
    2  09:34:59  09:40:53  Profile2
    3  09:47:23  09:53:33  Profile3
    4  09:54:44  09:57:13      Run2
    5  10:02:21  10:07:58      Run3
    6  10:09:37  10:12:43      Run4