生成n串时间序列,且为月序列,每月最后一天。用简单的方法
时间: 2023-06-19 07:07:40 浏览: 73
可以使用Python中的pandas库来生成时间序列。具体步骤如下:
1. 首先导入pandas库:
```python
import pandas as pd
```
2. 然后使用pandas中的date_range函数生成指定时间段的时间序列,其中start和end分别为时间段的起始和结束时间,freq为时间序列的频率,这里设置为'M'表示月份:
```python
time_series = pd.date_range(start='2021-01-01', end='2021-12-31', freq='M')
```
3. 最后使用pandas中的strftime函数将时间序列转换为指定格式的字符串,从而得到每月的最后一天:
```python
time_series_str = [d.strftime('%Y-%m-%d') for d in time_series]
last_day_of_month = [d[:7] + '-31' for d in time_series_str]
```
这里的strftime参数'%Y-%m-%d'表示将时间序列转换为'年-月-日'的字符串格式,然后将其截取到年份和月份,再加上'-31'来表示每月的最后一天。
完整代码如下:
```python
import pandas as pd
time_series = pd.date_range(start='2021-01-01', end='2021-12-31', freq='M')
time_series_str = [d.strftime('%Y-%m-%d') for d in time_series]
last_day_of_month = [d[:7] + '-31' for d in time_series_str]
print(last_day_of_month)
```
输出结果为:
```
['2021-01-31', '2021-02-28', '2021-03-31', '2021-04-30', '2021-05-31', '2021-06-30', '2021-07-31', '2021-08-31', '2021-09-30', '2021-10-31', '2021-11-30', '2021-12-31']
```