How to remove seconds from datetime?

前端 未结 10 1972
终归单人心
终归单人心 2021-02-20 13:02

I have the following date and I tried the following code,

df[\'start_date_time\'] = [\"2016-05-19 08:25:00\",\"2016-05-19 16:00:00\",\"2016-05-20 07:45:00\",\"20         


        
10条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 13:42

    Convert String to datetime object first, then you can use the replace method.

    from _datetime import *
    
    
    df = dict()
    df['start_date_time'] = ["2016-05-19 08:25:00",
                             "2016-05-19 16:00:00",
                             "2016-05-20 07:45:00",
                             "2016-05-24 12:50:00",
                             "2016-05-25 23:00:00",
                             "2016-05-26 19:45:00"]
    
    for dt in df['start_date_time']:
        cur_dt = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
        cur_dt = cur_dt.replace(second=0)
        print(cur_dt)
    
        cur_dt_without_second = cur_dt.strftime('%Y-%m-%d %H:%M')
        print(cur_dt_without_second)
    
    -------------------
    2016-05-19 08:25:00
    2016-05-19 08:25
    2016-05-19 16:00:00
    2016-05-19 16:00
    2016-05-20 07:45:00
    2016-05-20 07:45
    2016-05-24 12:50:00
    2016-05-24 12:50
    2016-05-25 23:00:00
    2016-05-25 23:00
    2016-05-26 19:45:00
    2016-05-26 19:45
    

提交回复
热议问题