Typeerror: strptime() argument 1 must be str, not series

Error: TypeError: strptime() argument 1 must be str, not series


Description:

This error occurs when using the strptime() function from the datetime module with a series as the first argument, instead of a string.
The strptime() function is used to convert a string representing a date and time to a datetime object.

However, if you pass a series (e.g., a column from a pandas DataFrame) to strptime(), it will raise a TypeError since it expects a string.

Example:

    
import pandas as pd
from datetime import datetime

# Create a DataFrame with a date column
data = {'date': ['2022-01-01', '2022-02-01', '2022-03-01']}
df = pd.DataFrame(data)

# Try to convert the date column to datetime using strptime()
df['date'] = datetime.strptime(df['date'], '%Y-%m-%d')
    
  


The above code will raise the TypeError: strptime() argument 1 must be str, not series.
To fix this error, you need to apply the strptime() function to each element in the series using the apply() function.
Here’s an updated example:

    
import pandas as pd
from datetime import datetime

# Create a DataFrame with a date column
data = {'date': ['2022-01-01', '2022-02-01', '2022-03-01']}
df = pd.DataFrame(data)

# Convert the date column to datetime using apply() and strptime()
df['date'] = df['date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))
    
  

Same cateogry post

Leave a comment