pd.to_datetime使用方法
时间: 2023-11-09 13:14:36 浏览: 130
python中时间转换datetime和pd.to_datetime详析
pd.to_datetime方法用于将字符串或类似日期的对象转换为pandas的日期时间类型。以下是使用pd.to_datetime的示例:
1. 将字符串转换为日期时间类型:
```python
import pandas as pd
date_str = '2022-01-01'
date_time = pd.to_datetime(date_str)
print(date_time)
```
输出:
```python
2022-01-01 00:00:00
```
2. 将多个字符串转换为日期时间类型:
```python
date_str_list = ['2022-01-01', '2022-01-02', '2022-01-03']
date_time_list = pd.to_datetime(date_str_list)
print(date_time_list)
```
输出:
```python
DatetimeIndex(['2022-01-01', '2022-01-02', '2022-01-03'], dtype='datetime64[ns]', freq=None)
```
3. 将日期时间字符串转换为指定格式的日期时间类型:
```python
date_time_str = '2022/01/01 12:00:00'
date_time = pd.to_datetime(date_time_str, format='%Y/%m/%d %H:%M:%S')
print(date_time)
```
输出:
```python
2022-01-01 12:00:00
```
4. 将日期时间字符串转换为UTC时间:
```python
date_time_str = '2022/01/01 12:00:00'
date_time = pd.to_datetime(date_time_str, format='%Y/%m/%d %H:%M:%S').tz_localize('UTC')
print(date_time)
```
输出:
```python
2022-01-01 12:00:00+00:00
```
阅读全文