Reputation: 11
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)
Upvotes: 1
Views: 1552
Reputation: 9
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')
Upvotes: 0
Reputation: 29992
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
Upvotes: 1
Reputation: 1183
%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)
Upvotes: 1
Reputation: 19
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
Upvotes: 0