Python Pandas – 使用DateTimeIndex创建日期时间
要创建日期时间,我们将使用date_range()函数。周期和时区也将使用频率一起设置。首先,导入所需的库−
import pandas as pd
在以澳大利亚/悉尼为时区、周期为8且频率为M即月份的情况下创建DatetimeIndex−
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')
显示日期时间−
print("日期时间...\n", datetime)
示例
以下是代码−
import pandas as pd
# DatetimeIndex with period 8 and frequency as M i.e. months
# timezone is Australia/Sydney
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')
# display
print("日期时间...\n", datetime)
# get the day name
print("\n获取星期几..\n", datetime.day_name())
# get the month name
print("\n获取月份..\n", datetime.month_name())
# get the year
print("\n获取年份..\n", datetime.year)
# get the hour
print("\n获取小时..\n", datetime.hour)
# get the minutes
print("\n获取分钟..\n", datetime.minute)
# get the seconds
print("\n获取秒数..\n", datetime.second)
输出结果
代码将产生以下输出−
日期时间...
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')
获取星期几..
Index(['Thursday', 'Sunday', 'Tuesday', 'Friday', 'Monday', 'Monday','Thursday', 'Saturday'],
dtype='object')
获取月份..
Index(['September', 'October', 'November', 'December', 'January', 'February','March', 'April'], dtype='object')
获取年份..
Int64Index([2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022], dtype='int64')
获取小时..
Int64Index([2, 2, 2, 2, 2, 2, 2, 2], dtype='int64')
获取分钟..
Int64Index([35, 35, 35, 35, 35, 35, 35, 35], dtype='int64')
获取秒数..
Int64Index([55, 55, 55, 55, 55, 55, 55, 55], dtype='int64')