在 Pandas 中读取日期和时间数据

在 Python 中处理日期和时间

Max Shron

Data Scientist and Author

一个简单的 Pandas 示例

# 加载 Pandas
import pandas as pd

# 导入 W20529 在 2017 年 Q4 的骑行 rides = pd.read_csv('capital-onebike.csv')
在 Python 中处理日期和时间

一个简单的 Pandas 示例

# 查看数据
print(rides.head(3))

           Start date            End date                  Start station  \
0 2017-10-01 15:23:25 2017-10-01 15:26:26           Glebe Rd & 11th St N
1 2017-10-01 15:42:57 2017-10-01 17:49:59  George Mason Dr & Wilson Blvd
2 2017-10-02 06:37:10 2017-10-02 06:42:53  George Mason Dr & Wilson Blvd

                            End station Bike number Member type
0         George Mason Dr & Wilson Blvd      W20529      Member
1         George Mason Dr & Wilson Blvd      W20529      Casual
2  Ballston Metro / N Stuart & 9th St N      W20529      Member
在 Python 中处理日期和时间

一个简单的 Pandas 示例

rides['Start date']
0     2017-10-01 15:23:25
1     2017-10-01 15:42:57
...
Name: Start date, Length: 290, dtype: object
rides.iloc[2]
Start date                               2017-10-02 06:37:10
End date                                 2017-10-02 06:42:53
...
Name: 1, dtype: object
在 Python 中处理日期和时间

使用 parse_dates 加载日期时间

# 导入 W20529 在 2017 年 Q4 的骑行
rides = pd.read_csv('capital-onebike.csv',
                    parse_dates = ['Start date', 'End date'])

# 或者: rides['Start date'] = pd.to_datetime(rides['Start date'], format = "%Y-%m-%d %H:%M:%S")
在 Python 中处理日期和时间

使用 parse_dates 加载日期时间

# 选择第 2 行的 Start date
rides['Start date'].iloc[2]
Timestamp('2017-10-02 06:37:10')
在 Python 中处理日期和时间

支持时区的运算

# 创建时长列
rides['Duration'] = rides['End date'] - rides['Start date']

# 打印前 5 行 print(rides['Duration'].head(5))
0 0 days 00:03:01 
1 0 days 02:07:02 
2 0 days 00:05:43 
3 0 days 00:21:18 
4 0 days 00:21:17 
Name: Duration, dtype: timedelta64[ns]
在 Python 中处理日期和时间

使用 parse_dates 加载日期时间

rides['Duration']\
  .dt.total_seconds()\
  .head(5)
0     181.0
1    7622.0
2     343.0
3    1278.0
4    1277.0
Name: Duration, dtype: float64
在 Python 中处理日期和时间

在 Pandas 中读取日期和时间数据

在 Python 中处理日期和时间

Preparing Video For Download...