引言
在我们进行一些时间序列问题时,往往要对日期型数据进行分析处理,本章介绍一下如何使用python处理日期型数据
💮1. 将字符串转换成日期
python
# 导入相关库;
import pandas as pd
import numpy as np
python
# 创建字符串
date_strings = np.array(['03-04-2005 11:35 PM',
'23-05-2010 12:01 AM',
'04-09-2009 09:09 PM'])
python
# 转换成datetime 类型的数据
[pd.to_datetime(date, format='%d-%m-%Y %I:%M %p') for date in date_strings]
sql
[Timestamp('2005-04-03 23:35:00'),
Timestamp('2010-05-23 00:01:00'),
Timestamp('2009-09-04 21:09:00')]
python
# 我们还可以增加errors参数来处理错误
# 转换成datetime类型的数据
[pd.to_datetime(date, format='%d-%m-%Y %I:%M %p', errors = 'coerce') for date in date_strings]
sql
[Timestamp('2005-04-03 23:35:00'),
Timestamp('2010-05-23 00:01:00'),
Timestamp('2009-09-04 21:09:00')]
当传入errors = 'coerce'
参数时,即使转换错误也不会报错,但是会将错误的值返回为Nan
(缺失值)
🏵️2. 处理时区
一般而言,pandas的对象默认是没有时区的,不过我们也可以在创建对象时通过tz参数指定时区
python
import pandas as pd
python
# 创建一个dataframe
pd.Timestamp('2017-05-01 06:00:00', tz = 'Europe/London')
ini
Timestamp('2017-05-01 06:00:00+0100', tz='Europe/London')
python
# 可以使用tz_locallize添加时区信息
data = pd.Timestamp('2017-05-01 06:00:00')
python
# 设置时区
data_in_london = data.tz_localize('Europe/London')
python
data_in_london
ini
Timestamp('2017-05-01 06:00:00+0100', tz='Europe/London')
python
# 我们还可以使用tz_convert来转换时区
data_in_london.tz_convert('Asia/Chongqing')
ini
Timestamp('2017-05-01 13:00:00+0800', tz='Asia/Chongqing')
python
# Series对象还可以对每一个元素应用tz_localiz和tz_convert
dates = pd.Series(pd.date_range('2002-02-02', periods=3, freq='M'))
python
# 设置时区
dates.dt.tz_localize('Asia/Chongqing')
yaml
0 2002-02-28 00:00:00+08:00
1 2002-03-31 00:00:00+08:00
2 2002-04-30 00:00:00+08:00
dtype: datetime64[ns, Asia/Chongqing]
🌹3. 选择日期和时间
python
dataframe = pd.DataFrame()
python
dataframe['date'] = pd.date_range('2001-01-01 01:00:00', periods=100000, freq='H')
删选两个日期之间的观察值, 用 &
来表示且的关系
python
dataframe[(dataframe['date']>'2002-01-01 01:00:00') & (dataframe['date']<='2002-1-1 04:00:00')]
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
| | date |
| 8761 | 2002-01-01 02:00:00 |
| 8762 | 2002-01-01 03:00:00 |
8763 | 2002-01-01 04:00:00 |
---|
另一种方法,将date这一列设为索引,然后用loc删选
python
dataframe = dataframe.set_index(dataframe['date'])
python
dataframe.loc['2002-1-1 01:00:00':'2002-1-1 04:00:00']
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
| | date |
| date | |
| 2002-01-01 01:00:00 | 2002-01-01 01:00:00 |
| 2002-01-01 02:00:00 | 2002-01-01 02:00:00 |
| 2002-01-01 03:00:00 | 2002-01-01 03:00:00 |
2002-01-01 04:00:00 | 2002-01-01 04:00:00 |
---|
🌺4. 将数据切分成多个特征
python
df = pd.DataFrame()
df['date'] = pd.date_range('1/1/2001', periods=150, freq='w')
创建年月日时分的特征
python
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df['hour'] = df['date'].dt.hour
df['minute'] = df['date'].dt.minute
python
df.head()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
| | date | year | month | day | hour | minute |
| 0 | 2001-01-07 | 2001 | 1 | 7 | 0 | 0 |
| 1 | 2001-01-14 | 2001 | 1 | 14 | 0 | 0 |
| 2 | 2001-01-21 | 2001 | 1 | 21 | 0 | 0 |
| 3 | 2001-01-28 | 2001 | 1 | 28 | 0 | 0 |
4 | 2001-02-04 | 2001 | 2 | 4 | 0 | 0 |
---|
🌻5.计算两个日期之间的时间差
python
import pandas as pd
dataframe = pd.DataFrame()
dataframe['Arrived'] = [pd.Timestamp('01-01-2017'), pd.Timestamp('01-04-2017')]
dataframe['left'] = [pd.Timestamp('01-01-2017'), pd.Timestamp('01-06-2017')]
python
# 计算两个特征直接的时间间隔
dataframe['left'] - dataframe['Arrived']
ini
0 0 days
1 2 days
dtype: timedelta64[ns]