1

I have couple columns in df with avg time, example "0 days 00:00:21". I want convert all columns to datetime.time format "hh:mm:ss" without "0 days". How can I do this?

my df

1
  • You can't convert a timedelta to a datetime (that simply doesn't make sense). Do you actually have datetime.timedelta objects in the DF? What's your end goal here with the format? Commented Mar 25, 2024 at 9:10

2 Answers 2

0

Should be fine with that code

For 4 columns, u can create a list of column names that u want to change. After that, put into for loop to iterate all column names that u want to change. It'll convert columns.

column_names = ["first","second","third","fourth"]

for name in column_names:
    df[name] = df[name].dt.seconds.apply(lambda x: pd.to_datetime(x, unit='s').time())
Sign up to request clarification or add additional context in comments.

8 Comments

it's working but only for one column, i have in my df 9 columns and i need change 4 columns and leave the rest unchanged
can u sent your all table so I can take look according that. @GrzegorzZ
I attached an image in the first message
@GrzegorzZ I changed code, u can put your column names which u want to change into column_names list and it will convert all your columns
it's working :-) maybe you know why I'm getting the message? "A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"
|
0

not sure how you data is stored.. but you could try something like this:

# Example DataFrame
data = {'time1': ['0 days 00:00:21', '0 days 00:01:15', '0 days 00:02:45'],
        'time2': ['0 days 00:00:35', '0 days 00:00:50', '0 days 00:03:10']}
df = pd.DataFrame(data)

# Convert columns to timedelta objects
df[['time1', 'time2']] = df[['time1', 'time2']].apply(pd.to_timedelta)

# Extract time component and convert to string
df[['time1', 'time2']] = df[['time1', 'time2']].applymap(lambda x: x.seconds)

# Convert seconds to hh:mm:ss format
df[['time1', 'time2']] = df[['time1', 'time2']].applymap(lambda x: pd.to_datetime(x, unit='s').time())

print(df)`

5 Comments

my df have 9 columns: dtypes: int32(1), int64(3), object(2), timedelta64[ns](4). "unit='s' not valid with non-numerical val='0 days 00:00:21', at position 0 "
what data type is the avg time value?
timedelta64[ns]
ok, you need to provide a reproducible data in a format I can see.
I attached an image in the first message

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.