Home > Backend Development > Python Tutorial > How Can Pandas Efficiently Convert String Dates to DateTime Objects and Filter by Date Range?

How Can Pandas Efficiently Convert String Dates to DateTime Objects and Filter by Date Range?

Barbara Streisand
Release: 2024-11-26 12:21:09
Original
733 people have browsed it

How Can Pandas Efficiently Convert String Dates to DateTime Objects and Filter by Date Range?

Converting String Formats to Datetime Format in Pandas

Pandas provides a convenient way to convert string values representing dates and times into datetime objects. The pd.to_datetime() function can handle a variety of input string formats, automatically detecting the correct format based on the value's contents.

Consider the following column of string values representing dates:

I_DATE
28-03-2012 2:15:00 PM
28-03-2012 2:17:28 PM
28-03-2012 2:50:50 PM
Copy after login

To convert I_DATE to datetime format, simply use pd.to_datetime(df['I_DATE']). Since the format is straightforward, pandas will automatically identify it.

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0    2012-03-28 14:15:00
1    2012-03-28 14:17:28
2    2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]
Copy after login

You can also access specific components of the datetime object using the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object
Copy after login

Filtering Data Based on Date Ranges

Once your data is in datetime format, you can easily filter based on date ranges. For example, to filter the df DataFrame for rows where I_DATE falls within a specific range, you can use:

df[(df['I_DATE'] > '2015-02-04') & (df['I_DATE'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09
Copy after login

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

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