Home > Backend Development > Python Tutorial > How to Convert String Dates to Datetime Objects and Filter by Date Range in Pandas?

How to Convert String Dates to Datetime Objects and Filter by Date Range in Pandas?

Linda Hamilton
Release: 2024-12-01 05:27:14
Original
265 people have browsed it

How to Convert String Dates to Datetime Objects and Filter by Date Range in Pandas?

Converting Strings to Datetime Format in Pandas

Problem:

Given a Pandas dataframe with a column containing string date values, how do you convert these values to the datetime format? Additionally, how can you filter rows based on a specified range of dates?

Solution:

Conversion to Datetime Format:

To convert strings to datetime format in Pandas, use the to_datetime function. In general, the parser can automatically determine the format of the input string, eliminating the need for explicit format specification.

import pandas as pd

df = pd.DataFrame({'I_DATE': ['28-03-2012 2:15:00 PM', '28-03-2012 2:17:28 PM', '28-03-2012 2:50:50 PM']})

df['I_DATE'] = pd.to_datetime(df['I_DATE'])
Copy after login

This code converts the I_DATE column to datetime format. The output looks like this:

   I_DATE
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Copy after login

Accessing Date Components:

After conversion, you can access individual date components, such as the date, time, or day, using the dt accessor. For example:

# Get the date only
df['I_DATE'].dt.date

# Get the time only
df['I_DATE'].dt.time
Copy after login

Filtering Rows Based on Date Range:

To filter rows based on a range of dates, use the following syntax:

df[(df['date'] > 'start_date') & (df['date'] < 'end_date')]
Copy after login

For instance, to filter rows where the dates are between '2015-02-04' and '2015-02-10':

df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]
Copy after login

The above is the detailed content of How to Convert String Dates to Datetime Objects and Filter by Date Range in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template