Python Pandas - 使用 DateTimeIndex 创建日期时间
要创建日期时间,我们将使用date_range().周期和时区也将与频率一起设置。首先,导入所需的库-
import pandas as pd
DatetimeIndex周期为8,频率为M,即月。时区是澳大利亚/悉尼-
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')显示日期时间-
print("DateTime...\n", datetime)示例
以下是代码-
import pandas as pd
#DatetimeIndex,周期为8,频率为M即月
#时区是澳大利亚/悉尼
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')
#展示
print("DateTime...\n", datetime)
#获取日期名称
print("\nGetting the day name..\n",datetime.day_name())
#获取月份名称
print("\nGetting the month name..\n",datetime.month_name())
#得到年份
print("\nGetting the year name..\n",datetime.year)
#得到小时
print("\nGetting the hour..\n",datetime.hour)
#得到分钟
print("\nGetting the minutes..\n",datetime.minute)
#得到秒
print("\nGetting the seconds..\n",datetime.second)输出结果这将产生以下输出-
DateTime...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
'2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
'2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00',
'2022-03-31 02:35:55+11:00', '2022-04-30 02:35:55+10:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='M')
Getting the day name..
Index(['Thursday', 'Sunday', 'Tuesday', 'Friday', 'Monday', 'Monday','Thursday', 'Saturday'],
dtype='object')
Getting the month name..
Index(['September', 'October', 'November', 'December', 'January', 'February','March', 'April'], dtype='object')
Getting the year name..
Int64Index([2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022], dtype='int64')
Getting the hour..
Int64Index([2, 2, 2, 2, 2, 2, 2, 2], dtype='int64')
Getting the minutes..
Int64Index([35, 35, 35, 35, 35, 35, 35, 35], dtype='int64')
Getting the seconds..
Int64Index([55, 55, 55, 55, 55, 55, 55, 55], dtype='int64')