Extracting the first day of month of a datetime type column in pandas

前端 未结 8 1182
你的背包
你的背包 2020-12-14 06:11

I have the following dataframe:

user_id    purchase_date 
  1        2015-01-23 14:05:21
  2        2015-02-05 05:07:30
  3        2015-02-18 17:08:51
  4            


        
8条回答
  •  無奈伤痛
    2020-12-14 06:34

    @Eyal: This is what I did to get the first day of the month using pd.offsets.MonthBegin and handle the scenario where day is already first day of month.

    import datetime
    
    from_date= pd.to_datetime('2018-12-01')
    
    from_date = from_date - pd.offsets.MonthBegin(1, normalize=True) if not from_date.is_month_start else from_date
    
    from_date
    

    result: Timestamp('2018-12-01 00:00:00')

    from_date= pd.to_datetime('2018-12-05')
    
    from_date = from_date - pd.offsets.MonthBegin(1, normalize=True) if not rom_date.is_month_start else from_date
    
    from_date
    

    result: Timestamp('2018-12-01 00:00:00')

提交回复
热议问题