如何将pandas偏移量转换为Python日期?
在本文中,我们将在Python中将pandas偏移转换为日期。当您从日期对象中减去pandas时,您会得到一个pandas Timestamp对象。您可以将此对象转换为字符串格式日期或日期对象(标准Python日期)。或者您可以使用datetime库中的timedelta对象。
例1
在以下示例代码中,我们使用to_offset(“10D”)从pandas pd.to_datetime(’2018-01-04’)中删除10天的偏移量。
from pandas.tseries.frequencies import to_offset
import pandas as pd
dt = pd.to_datetime('2018-01-04') - to_offset("10D")
print(type(dt))
print(dt)
输出
上述代码的输出如下所示。
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
2017-12-25 00:00:00
在上述输出中,我们可以观察到“dt”变量是一个字符串。要将此字符串转换为给定格式,您可以使用strftime。要将此字符串转换为日期对象,您可以使用date()函数。
例2
在以下示例代码中,我们使用strftime()方法将字符串“2017-12-25 00:00:00”转换为“yy-mm-dd”格式。要将此字符串转换为日期对象,我们使用date()函数。
from pandas.tseries.frequencies import to_offset
import pandas as pd
dt = pd.to_datetime('2018-01-04') - to_offset("10D")
print(dt.strftime('%Y-%m-%d'))
print(dt.date())
print(type(dt.date()))
输出
上述代码的输出如下所示。
2017-12-25
2017-12-25
<class 'datetime.date'>
例3
以下是使用pandas delta将pandas Offset转换为python日期的示例−
from pandas.tseries.frequencies import to_offset
import pandas as pd
dt = pd.to_datetime('2018-01-04') - pd.Timedelta('10D')
print(dt.strftime('%Y-%m-%d'))
print(dt.date())
print(type(dt.date()))
输出
2017-12-25
2017-12-25
<class 'datetime.date'>
例4
可以使用to_timedelta()而不是Timedelta()−
from pandas.tseries.frequencies import to_offset
import pandas as pd
dt = pd.to_datetime('2022-09-10') - pd.to_timedelta('10D')
print(dt.date())
输出结果
2022-08-31