Python Pandas - 返回由日期格式指定的格式化字符串的索引
要返回由日期格式指定的格式化字符串的索引,请使用Pandas中的方法。DateTimeIndex.strftime()
首先,导入所需的库-
import pandas as pd
创建一个日期时间索引,周期为7,频率为D即天-
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='2D')
显示日期时间索引-
print("DateTimeIndex...\n", datetimeindex)
格式化-
print("\nFormat with different directives...\n", datetimeindex.strftime('%b. %d, %Y was a %A'))
示例
以下是代码-
import pandas as pd #DatetimeIndexwithperiod7andfrequencyasDi.e.days #ThetimezoneisAustralia/Adelaide datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='2D') #displayDateTimeIndex print("DateTimeIndex...\n", datetimeindex) #displayDateTimeIndex frequency print("\nDateTimeIndex frequency...\n", datetimeindex.freq) #displaytheresult print("\nFormat with different directives...\n", datetimeindex.strftime('%b. %d, %Y was a %A'))输出结果
这将产生以下代码-
DateTimeIndex... DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-11-01 02:30:50+10:30', '2021-11-03 02:30:50+10:30', '2021-11-05 02:30:50+10:30', '2021-11-07 02:30:50+10:30', '2021-11-09 02:30:50+10:30', '2021-11-11 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='2D') DateTimeIndex frequency... <2 * Days> Format with different directives... Index(['Oct. 30, 2021 was a Saturday', 'Nov. 01, 2021 was a Monday', 'Nov. 03, 2021 was a Wednesday', 'Nov. 05, 2021 was a Friday', 'Nov. 07, 2021 was a Sunday', 'Nov. 09, 2021 was a Tuesday', 'Nov. 11, 2021 was a Thursday'], dtype='object')