Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chuyển đổi pandas offset thành date Python?


Khi trừ một pandas offset từ đối tượng date, kết quả là đối tượng pandas.Timestamp. Bạn có thể chuyển đổi đối tượng này sang chuỗi định dạng date hoặc đối tượng date chuẩn của Python. Hoặc dùng đối tượng timedelta từ thư viện datetime.

Ví dụ

from pandas.tseries.frequencies import to_offset
import pandas as pd
dt = pd.to_datetime('2018-01-04') - to_offset("5D")
print(type(dt))

Kết quả

<class 'pandas._libs.tslib.Timestamp'>

Để chuyển sang chuỗi định dạng, dùng strftime(). Để chuyển sang date object chuẩn, dùng phương thức date().

Ví dụ

from pandas.tseries.frequencies import to_offset
import pandas as pd
dt = pd.to_datetime('2018-01-04') - to_offset("5D")
print(dt.strftime('%Y-%m-%d'))
print(dt.date())
print(type(dt.date()))

Kết quả

2017-12-30
2017-12-30
<class 'datetime.date'>

Mẹo: Từ pandas 1.0+, có thể dùng pd.Timestamp(...).date() trực tiếp. to_offset hữu ích cho offset phức tạp như '1M', '3B' (business days).