Pandas - convert strings to time without date

前端 未结 3 2017
感情败类
感情败类 2020-11-27 04:33

I\'ve read loads of SO answers but can\'t find a clear solution.

I have this data in a df called day1 which represents hours:

1    10:53         


        
3条回答
  •  醉话见心
    2020-11-27 05:24

    After performing the conversion you can use the datetime accessor dt to access just the hour or time component:

    In [51]:
    
    df['hour'] = pd.to_datetime(df['time'], format='%H:%M').dt.hour
    df
    Out[51]:
            time  hour
    index             
    1      10:53    10
    2      12:17    12
    3      14:46    14
    4      16:36    16
    5      18:39    18
    6      20:31    20
    7      22:28    22
    

    Also your format string H%:M% is malformed, it's likely to raise a ValueError: ':' is a bad directive in format 'H%:M%'

    Regarding your last comment the dtype is datetime.time not datetime:

    In [53]:
    df['time'].iloc[0]
    
    Out[53]:
    datetime.time(10, 53)
    

提交回复
热议问题