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 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告