pd.to_datetime用法
时间: 2023-10-11 13:09:39 浏览: 123
`pd.to_datetime()` 是 pandas 库中一个用于将日期字符串或日期序列转换为日期格式的函数。
常见用法如下:
1. 将单个日期字符串转换为日期格式:
```python
import pandas as pd
date_str = '2022-01-01'
date = pd.to_datetime(date_str)
print(date)
# 输出:2022-01-01 00:00:00
```
2. 将日期字符串序列转换为日期格式序列:
```python
import pandas as pd
date_strs = ['2022-01-01', '2022-02-01', '2022-03-01']
dates = pd.to_datetime(date_strs)
print(dates)
# 输出:DatetimeIndex(['2022-01-01', '2022-02-01', '2022-03-01'], dtype='datetime64[ns]', freq=None)
```
3. 将日期字符串序列转换为日期格式序列,并指定日期格式:
```python
import pandas as pd
date_strs = ['01-01-2022', '02-01-2022', '03-01-2022']
dates = pd.to_datetime(date_strs, format='%m-%d-%Y')
print(dates)
# 输出:DatetimeIndex(['2022-01-01', '2022-02-01', '2022-03-01'], dtype='datetime64[ns]', freq=None)
```
4. 将包含日期字符串的 DataFrame 列转换为日期格式列:
```python
import pandas as pd
df = pd.DataFrame({'date_str': ['2022-01-01', '2022-02-01', '2022-03-01']})
df['date'] = pd.to_datetime(df['date_str'])
print(df)
# 输出:
# date_str date
# 0 2022-01-01 2022-01-01
# 1 2022-02-01 2022-02-01
# 2 2022-03-01 2022-03-01
```
阅读全文