Python Pandas - 返回 Python datetime.date 对象的 numpy 数组


要返回 Python datetime.date 对象的 numpy 数组,请在 Pandas 中使用 datetimeindex.date 属性。

首先,导入所需的库 −

import pandas as pd

创建一个周期为 3 且频率为 us(即纳秒)的 DatetimeIndex −

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')

显示 DateTimeIndex −

print("DateTimeIndex...\n", datetimeindex)

仅返回时间戳的日期部分,而不包含时区信息 −

print("\nThe numpy array (date part)..\n",datetimeindex.date)

示例

以下为该代码 −

import pandas as pd

# DatetimeIndex with period 3 and frequency as us i.e. nanoseconds
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# Returns only the date part of Timestamps without timezone information
print("\nThe numpy array (date part)..\n",datetimeindex.date)

输出

这将产生以下代码 −

DateTimeIndex...
DatetimeIndex([ '2021-10-20 02:30:50+11:00',
'2021-10-20 02:30:50.000000001+11:00',
'2021-10-20 02:30:50.000000002+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='N')

The numpy array (date part)..
[datetime.date(2021, 10, 20) datetime.date(2021, 10, 20)
datetime.date(2021, 10, 20)]

更新于: 2021 年 10 月 18 日

567 次浏览

开启你的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.