简体   繁体   中英

In dataframe: how to pull minutes and seconds combinedly(mm:ss) from timedelta using python

i have already tried these but by this we can only get hour/minute/second but not both minute and second

In[7]: df['B'] = df['A'].dt.components['hours']

df

Out[7]:

     A  B

0 02:00:00 2

1 01:00:00 1


from this timedelta format

0 0 days 00:02:02.246000

1 0 days 00:01:59.127000

i need only minutes and seconds, how to get it as below

02:02

01:59

You can convert the timedelta to total seconds and use divmod function to extract minutes and seconds from the total seconds.

Edit: Removed lambda function from the first operation.

    df['sec'] = df['A'].dt.total_seconds().astype(int)
    df['B'] = df.apply(lambda row: str(divmod(divmod(row['sec'], 3600)[1], 60)[0]).zfill(2)+':'+str(divmod(divmod(row['sec'], 3600)[1], 60)[1]).zfill(2), axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM