Home > OS >  Convert a time column with extra digits to a full time columns to hours:mins:secs
Convert a time column with extra digits to a full time columns to hours:mins:secs

Time:04-16

I am working on a time series data frame.The df is as follows:

0   2019-01-01  Contact    Tuesday  False   January 04:00:00.118000 1
1   2019-01-01  Contact    Tuesday  False   January 04:00:00.483000 1
2   2019-01-01  Contact    Tuesday  False   January 08:00:00.162000 1
3   2019-01-01  Contact    Tuesday  False   January 08:00:00.426000 1
4   2019-01-01  Contact    Tuesday  False   January 08:00:00.564000 1

To get this df I have done other transformation above hence, this is not a direct load. so I am trying to convert the second last column with 04:00:00.118000 to 04:00:00. What is the quickest way to achieve this?

CodePudding user response:

If your entries in the second to last column are of type datetime.time, you could use the following:

df[name] = df[name].apply(lambda t: t.replace(microsecond=0))

where name is the name of your second to last column. If they are of type str, then you could use this instead:

df[name] = df[name].apply(lambda t: t.split('.')[0])

CodePudding user response:

Try this, if you have the Object type data then it should work..

Sample data mimicking the data ..

>>> df
                      date  col1
0  January 04:00:00.118000     1
1  January 04:00:00.483000     1
2  January 08:00:00.162000     1
3  January 08:00:00.426000     1
>>> df.dtypes
date    object
col1     int64
dtype: object

Solution

>>> df['date'] = df['date'].str.split(".").str[0]
>>> df
               date  col1
0  January 04:00:00     1
1  January 04:00:00     1
2  January 08:00:00     1
3  January 08:00:00     1
  • Related