Pandas 如何将偏移转换为Python的日期

Pandas 如何将偏移转换为Python的日期

在本文中,我们将pandas的偏移转换为Python中的日期。当你从一个日期对象中减去pandas时,你会得到一个pandas时间戳对象。你可以将此对象转换为字符串格式的日期或日期对象(标准Python日期)。或者你可以使用datetime库中的timedelta对象。

示例1

在以下示例代码中,我们使用pandas的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偏移量转换为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

示例4

而不是 Timedelta() 我们也可以使用 to_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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程