Home > Mobile >  pandas python how to convert time duration to milliseconds?
pandas python how to convert time duration to milliseconds?

Time:12-22

I have a df ,you can have it by copy and run the following code:

import pandas as pd
from io import StringIO

df = """
 b_id          duration1                  duration2                          user

 384           28 days 21:05:16.141263     0 days 00:00:44.999706            Test
 
"""
df= pd.read_csv(StringIO(df.strip()), sep='\s\s ', engine='python')
df

My question is ,how can I convert the time duration from '28 days 21:05:16.141263' to milliseconds ?

CodePudding user response:

First convert your duration 1 into timedelta and then convert to milliseconds

df['duration1'] = pd.to_timedelta(df['duration1'])
df['dur1_milli'] = df['duration1'].astype(np.int64) / int(1e6)
print(df)

outputs #

   b_id               duration1               duration2  user    dur1_milli
0   384 28 days 21:05:16.141263  0 days 00:00:44.999706  Test  2.495116e 09

if you want to expand them expanded

Add this to the first line of your code

pd.set_option('display.float_format', lambda x: '%.3f' % x)

output #

   b_id               duration1               duration2  user     dur1_milli
0   384 28 days 21:05:16.141263  0 days 00:00:44.999706  Test 2495116141.263

CodePudding user response:

try this

df['duration1'].map(lambda x: pd.to_timedelta(x).total_seconds() * 1e3)

  • Related