how to use to_datetime
时间: 2023-10-11 08:10:55 浏览: 109
To use the to_datetime method in pandas, you first need to import the pandas library:
```
import pandas as pd
```
Then, you can call the to_datetime method and pass in a string or a list of strings representing the dates you want to convert:
```
date_string = '2021-11-11'
date_object = pd.to_datetime(date_string)
```
You can also pass in a list of strings to convert multiple dates at once:
```
date_strings = ['2021-11-11', '2021-11-12', '2021-11-13']
date_objects = pd.to_datetime(date_strings)
```
By default, the to_datetime method will return a pandas Timestamp object. However, you can also specify a different data type to return by passing in the desired type as an argument:
```
date_string = '2021-11-11'
date_object = pd.to_datetime(date_string, format='%Y-%m-%d', errors='coerce')
```
In this example, we've specified that we want the method to return a datetime64[ns] object instead of a Timestamp object. We've also specified a format string to match the input string and indicated that we want to coerce any errors that occur during the conversion to NaN values.
阅读全文