python数据清洗案例 把时间改为标准时间格式
时间: 2023-08-03 20:40:38 浏览: 57
一个常见的 Python 数据清洗案例是将时间数据转换为标准时间格式。假设有一个包含交易记录的数据集,其中包含交易时间的字符串数据。我们可以使用 Python 内置的 `datetime` 模块来将这些字符串转换为标准时间格式。
首先,我们需要导入 `datetime` 模块和包含数据的 CSV 文件:
```python
import csv
from datetime import datetime
with open('transactions.csv', 'r') as f:
reader = csv.reader(f)
next(reader) # skip header row
for row in reader:
transaction_time = row[3] # assuming transaction time is in column 3
# convert string to datetime object
dt = datetime.strptime(transaction_time, '%Y-%m-%d %H:%M:%S')
# convert datetime object to ISO format
iso_time = dt.isoformat()
# update row with new ISO format time
row[3] = iso_time
```
在上面的代码中,我们首先使用 `csv.reader` 对象读取 CSV 文件中的数据,并跳过第一行头信息。然后,我们迭代每一行数据,将交易时间的字符串转换为 `datetime` 对象,并将其转换为 ISO 格式的字符串。最后,我们更新每行数据中的交易时间,以便它包含新的 ISO 格式时间。
最后,我们可以将处理后的数据保存为新的 CSV 文件:
```python
with open('transactions_cleaned.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['col1', 'col2', 'col3', 'transaction_time']) # write header row
writer.writerows(rows)
```
这样就完成了将时间数据转换为标准时间格式的清洗处理。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)