Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Pandas để chuyển đổi một chuỗi ngày tháng thành thời gian

Trong chương trình này, chúng tôi sẽ chuyển đổi chuỗi ngày như "24 tháng 8 năm 2020" thành 2020-08-24 00:00:00. Chúng tôi sẽ sử dụng hàm to_datetime () trong thư viện gấu trúc để giải quyết công việc này.

Thuật toán

Step 1: Define a Pandas series containing date string.
Step 2: Convert these date strings into date time format using the to_datetime format().
Step 3: Print the results.

Mã mẫu

import pandas as pd

series = pd.Series(["24 August 2020", "25 December 2020 20:05"])
print("Series: \n", series)

datetime = pd.to_datetime(series)
print("DateTime Format: \n", datetime)

Đầu ra

Series:
0            24 August 2020
1    25 December 2020 20:05
dtype: object
DateTime Format:
0   2020-08-24 00:00:00
1   2020-12-25 20:05:00
dtype: datetime64[ns]