Python Pandas - 返回帶有時區資訊的 python datetime.time 物件的 numpy 陣列


如需使用時區資訊返回 python datetime.time 物件的 numpy 陣列,請使用 datetimeindex.timetz 屬性。

首先,匯入所需庫 −

import pandas as pd

使用週期為 5,頻率為 us(即納秒)建立 DatetimeIndex −

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

顯示 DateTimeIndex −

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

僅返回帶有時區資訊的時間戳的時間部分 −

print("\nThe numpy array (time part with timezone)..\n",datetimeindex.timetz)

示例

程式碼如下 −

import pandas as pd

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

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

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

輸出

將生成以下程式碼 −

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',
'2021-10-20 02:30:50.000000003+11:00',
'2021-10-20 02:30:50.000000004+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='N')

The numpy array (time part with timezone)..
[datetime.time(2, 30, 50, tzinfo=<DstTzInfo 'Australia/Sydney' AEDT+11:00:00 DST>)
datetime.time(2, 30, 50, tzinfo=<DstTzInfo 'Australia/Sydney' AEDT+11:00:00 DST>)
datetime.time(2, 30, 50, tzinfo=<DstTzInfo 'Australia/Sydney' AEDT+11:00:00 DST>)
datetime.time(2, 30, 50, tzinfo=<DstTzInfo 'Australia/Sydney' AEDT+11:00:00 DST>)
datetime.time(2, 30, 50, tzinfo=<DstTzInfo 'Australia/Sydney' AEDT+11:00:00 DST>)]

更新日期:2021 年 10 月 18 日

200 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.