Home >Backend Development >Python Tutorial >How Can I Convert Strings to Dates and Manipulate Dates in Pandas?

How Can I Convert Strings to Dates and Manipulate Dates in Pandas?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 13:16:15143browse

How Can I Convert Strings to Dates and Manipulate Dates in Pandas?

Converting Strings to Datetime 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn