Python Pandas - 判斷DateTimeIndex中的日期是否為當月第一天


要檢查DateTimeIndex中的日期是否為當月第一天,可以使用**DateTimeIndex.is_month_start**屬性。

首先,匯入所需的庫:

import pandas as pd

建立一個週期為6,頻率為D(即天)的DatetimeIndex。時區為澳大利亞/阿德萊德:

datetimeindex = pd.date_range('2021-9-21 02:30:50', periods=6, tz='Australia/Adelaide', freq='5D')

顯示DateTimeIndex:

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

檢查DateTimeIndex中的日期是否為當月第一天:

print("\nCheck whether the date in DateTimeIndex is the first day of the month...\n",
datetimeindex.is_month_start)

示例

以下是程式碼:

import pandas as pd

# DatetimeIndex with period 6 and frequency as D i.e. days
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-9-21 02:30:50', periods=6, tz='Australia/Adelaide', freq='5D')

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

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

# Check whether the date in DateTimeIndex is the first day of the month
print("\nCheck whether the date in DateTimeIndex is the first day of the month...\n",
datetimeindex.is_month_start)

輸出

這將產生以下程式碼:

DateTimeIndex...
DatetimeIndex(['2021-09-21 02:30:50+09:30', '2021-09-26 02:30:50+09:30',
'2021-10-01 02:30:50+09:30', '2021-10-06 02:30:50+10:30',
'2021-10-11 02:30:50+10:30', '2021-10-16 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='5D')
DateTimeIndex frequency...
<5 * Days>

Check whether the date in DateTimeIndex is the first day of the month...
[False False True False False False]

更新於:2021年10月18日

70 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.