python 把list中的月月日变成月
时间: 2023-10-05 11:04:37 浏览: 38
要把list中的月月日变成月,可以使用datetime模块中的strftime函数,将日期格式化成月份的形式。
以下是一个示例代码:
```python
import datetime
date_list = ['2022-01-01', '2022-02-02', '2022-03-03']
month_list = []
for date in date_list:
dt = datetime.datetime.strptime(date, '%Y-%m-%d')
month = dt.strftime('%m')
month_list.append(month)
print(month_list)
```
输出结果为:
```
['01', '02', '03']
```
在代码中,首先使用datetime模块中的strptime函数将日期字符串转换为datetime对象。然后使用strftime函数将datetime对象格式化为月份的形式。最后将月份添加到新的列表中。
相关问题
python把list中的内容写入到文件中
可以使用Python内置的文件操作函数将列表中的内容写入文件中。以下是一个示例代码:
```python
my_list = ["apple", "banana", "orange"]
with open("output.txt", "w") as file:
for item in my_list:
file.write(item + "\n")
```
这个代码将会把 `my_list` 中的每个元素分行写入 `output.txt` 文件中。其中 `open()` 函数用来打开文件,第一个参数是文件路径,第二个参数是打开模式,这里我们使用 `"w"` 表示写入模式,这样打开文件时如果文件不存在就会创建一个新文件。另外,使用 `with` 语句可以自动管理文件的打开和关闭,这样就不需要手动调用 `file.close()` 了。
python 把list 变成series
你可以使用 `pandas` 库中的 `Series()` 函数将一个 `list` 转换成 `Series` 对象。示例如下:
```python
import pandas as pd
my_list = [1, 2, 3, 4, 5]
my_series = pd.Series(my_list)
print(my_series)
```
输出结果为:
```
0 1
1 2
2 3
3 4
4 5
dtype: int64
```
其中,`pd.Series()` 函数将 `my_list` 转换成了一个整数类型的 `Series` 对象,并在输出中显示了每个元素的索引和值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)