"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > How to Convert a Pandas DataFrame Column to DateTime Format and Filter by Date?

How to Convert a Pandas DataFrame Column to DateTime Format and Filter by Date?

2025-03-26에 게시되었습니다
검색:708

How to Convert a Pandas DataFrame Column to DateTime Format and Filter by Date?

Transform Pandas DataFrame Column to DateTime Format

Scenario:

Data within a Pandas DataFrame often exists in various formats, including strings. When working with temporal data, timestamps may initially appear as strings but need to be converted to a datetime format for accurate analysis.

Conversion and Filtering Based on Date

To convert a string column to datetime in Pandas, utilize the to_datetime function. This function takes a format argument that specifies the expected format of the string column.

Example:

Consider the following DataFrame with a column (Mycol) containing strings in a custom format:

import pandas as pd

raw_data = pd.DataFrame({'Mycol': ['05SEP2014:00:00:00.000']})

To convert this column to datetime, use the following code:

df['Mycol'] = pd.to_datetime(df['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

The format argument specified matches the given string format. After conversion, the Mycol column will now contain datetime objects.

Date-Based Filtering

Once the column is converted to datetime, you can perform date-based filtering operations. For example, to select rows whose date falls within a specific range:

start_date = '01SEP2014'
end_date = '30SEP2014'
filtered_df = df[(df['Mycol'] >= pd.to_datetime(start_date)) & (df['Mycol'] <= pd.to_datetime(end_date))]

The resulting filtered_df will include only the rows where the Mycol column value is between the specified dates.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3