Home >Backend Development >Python Tutorial >How Can I Convert Strings to Dates and Manipulate Dates in Pandas?
Converting Strings to Datetime Format
To convert strings representing dates to datetime format, Pandas provides the pd.to_datetime() function. By default, it infers the format, as seen in the example:
df['I_DATE'] = pd.to_datetime(df['I_DATE'])
Specifying Input String Format
If the string format is unknown, specify it using the format parameter. For instance, to convert strings with the format "dd-mm-YYYY HH:MM:SS PM":
df['I_DATE'] = pd.to_datetime(df['I_DATE'], format="%d-%m-%Y %I:%M:%S %p")
Accessing Date/Time Components
Once converted to datetime, you can access specific components like date, day, or time using the dt accessor. For example, to get the date component:
df['I_DATE'].dt.date
Filtering Rows Based on Date Range
To filter rows based on a range of dates, use logical operators (>, <) on datetime objects:
df = pd.DataFrame({'date': pd.date_range(start='2015-01-01', end='2015-12-31')}) filtered_df = df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]This will return rows with dates within February 5th and 9th, 2015.
The above is the detailed content of How Can I Convert Strings to Dates and Manipulate Dates in Pandas?. For more information, please follow other related articles on the PHP Chinese website!