How do I round datetime column to nearest quarter hour

后端 未结 4 1506
北海茫月
北海茫月 2020-12-01 00:59

I have loaded a data file into a Python pandas dataframe. I has a datetime column of the format 2015-07-18 13:53:33.280.

What I need to do is create a

4条回答
  •  清歌不尽
    2020-12-01 01:12

    Assuming that your series is made up of datetime objects, You need to use Series.apply . Example -

    import datetime
    df[''] = df[''].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,15*(dt.minute // 15)))
    

    The above example to always round to the previous quarter hour (behavior similar to floor function).

    EDIT

    To round to the correct quarter hour (as in , if its 7 mins 30 seconds past previous quarter, to show the next quarter) . We can use the below example -

    import datetime
    df[''] = df[''].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,15*round((float(dt.minute) + float(dt.second)/60) / 15)))
    

    The above would only take the latest seconds into consideration , if you want the millisecond/microsecond into consideration , you can add that to the above equation as - (float(dt.minute) + float(dt.second)/60 + float(dt.microsecond)/60000000)

提交回复
热议问题