1

When I try to convert a string to time it doesn't work with the following code and I can't understand why could someone help me please ?

pd.to_datetime(movie_df['duration'], format='%M min')

I get this error :

ValueError: time data '93 min' does not match format '%M min' (match)

4 Answers 4

1

%M refers to "minutes" of the hour. (between 0 to 60 (exclusive)).

Further, "X min" is when forcefully converted to adatetime object will most likely lose its semantics.

>>> datetime.strptime('45 min', "%M min")
datetime.datetime(1900, 1, 1, 0, 45)

In the above example, even when the conversion does work, it's most likely not what you want (00:45 of 1st Jan 1900).

Looks like you are more dealing with durations and should not be using to_datetime function. Check out time-deltas, (and incidentally as @MrFuppens also points out,to_timedelta function)

Sign up to request clarification or add additional context in comments.

Comments

1

You could remove min in duration first, then convert it to pandas.TimedeltaIndex

movie_df['duration'] = movie_df['duration'].str.split(' ').str[0].astype(int)

movie_df['duration'] = pd.TimedeltaIndex(movie_df['duration'], unit='m').to_pytimedelta().astype(str)
print(movie_df)

  duration
0  1:33:00
1  1:42:00

Thanks for MrFuppes suggestion, you can use pandas.to_timedelta().

movie_df['duration'] = movie_df['duration'].str.split(' ').str[0].astype(int)
movie_df['duration'] = pd.to_timedelta(movie_df['duration'], unit='m').astype(str)
# print(movie_df)

          duration
0  0 days 01:33:00
1  0 days 01:42:00

1 Comment

Why not simply parse with pd.to_timedelta?
0

try to use this function: strptime () https://thispointer.com/python-string-to-datetime-or-date-object/#:~:text=Convert%20string%20to%20time%20object%20in%20Python%20In,overview%20of%20this%20function.%20Syntax%20of%20datetime.strptime%20%28%29

1 Comment

Link only answers are discouraged because links can break over time and render the answer useless. Please provide a summary of the solution here and why your answer may be preferable over the other answers already provided.
0

You are getting this error because the function does not know how to convert 93 min , because min should be < 60. So You can convert the duration to hours:min format. Eg: convert the 90 min to h:min string and run your time conversion on that.

df['duration'].apply(lambda x: str(int(x.split()[0])//60) +":"+ str(int(x.split()[0])%60)) 
pd.to_datetime(movie_df['duration'], format='%H:%M')

Comments

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.