2

I have a data frame and I am trying to convert the time column into a datetime format. The first step I did was:

data['time'] = data.time
data['time']=pd.to_datetime(data['time'], format='%H:%M:%S.%f')

This helped me successfully change the time column to:

dtype('\<M8\[ns\]')

But this gave me "1900-01-01" in every cell. My idea is to extract the time part from it by:

data['time']=data['time'].dt.time

That kind of works as well but the type got changed back to:

dtype('O')

Is there any way I can fix this?

3
  • 1
    Please edit the title of your question to be descriptive, unambiguous, and specific to what you are asking. For more guidance, see How do I write a good title?. Commented Nov 18 at 14:55
  • 1
    See how to make good reproducible pandas examples. Commented Nov 18 at 15:02
  • 1
    There is no native dtype for time-only values in pandas, so use timedelta or keep it as object. Commented Nov 18 at 23:30

1 Answer 1

2

You're converting a time into a datetime object, which contains a date too. The date "1900-01-01" is just a placeholder for the missing date information.

You should still be able to work with it directly:

data['time'].dt.hour      # get hours
data['time'].dt.minute    # get minutes
data['time'].dt.strftime('%H:%M:%S.%f')  # format for output

If you actually just wanted a duration, I'd recommend using timedelta for your data:


data['time'] = pd.to_timedelta(data['time'])
Sign up to request clarification or add additional context in comments.

1 Comment

No I don't want the duration, only the value in my column to be datetime format and stay like that. I did manage to do it, if you see in the above example but then it automatically changed back to object, so was just curious about this strange behaviour.

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.