Pandas 返回python datetime.time物件中的numpy陣列


要返回python datetime.time 物件的numpy陣列,請在Pandas中使用datetimeindex.time屬性。

首先,匯入所需的庫 -

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 (time part)..\n",datetimeindex.time)

示例

以下為程式碼 -

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)

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

輸出

以下為程式碼生成結果 -

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)]

The numpy array (time part)..
[datetime.time(2, 30, 50) datetime.time(2, 30, 50)
datetime.time(2, 30, 50)]

更新時間: 2021年10月18日

289次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告