与昨天时间 pandas 的时差
time difference in pandas with yesterday time
我有一个 pandas 数据框,其中包含以下格式的时间:
2017-05-02 00:00:00+00:00
2017-05-03 01:00:00+00:00
我想找出他们与前一天特定时间的区别,如上例:
2017-05-01 10:00:00
2017-05-02 10:00:00
我知道 timedelta 是解决方案,但我应该如何使用它?
使用 floor
,减去一天并在 Timedelata
秒内将 10 小时添加到从列 date
.
中减去的新 Series
日期
解决方案的优点是不需要创建辅助列然后删除它。
print (df)
date
0 2017-05-02 00:00:00+00:00
1 2017-05-03 01:00:00+00:00
#if necessary convert to datetime
df['date']= pd.to_datetime(df['date'])
dates = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (dates)
0 2017-05-01 10:00:00
1 2017-05-02 10:00:00
Name: date, dtype: datetime64[ns]
df['timedelta'] = df['date'] - dates
print (df)
date timedelta
0 2017-05-02 00:00:00 14:00:00
1 2017-05-03 01:00:00 15:00:00
对于 timedelata 的秒数,可以使用 total_seconds
and another solutions:
df['seconds'] = (df['date'] - dates).dt.total_seconds().astype(int)
print (df)
date seconds
0 2017-05-02 00:00:00 50400
1 2017-05-03 01:00:00 54000
相同的解决方案,如果还需要 new
列进行另一次处理,则只使用新列更好:
df['date']= pd.to_datetime(df['date'])
df['new'] = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (df)
date new
0 2017-05-02 00:00:00 2017-05-01 10:00:00
1 2017-05-03 01:00:00 2017-05-02 10:00:00
df['seconds'] = (df['date'] - df['new']).dt.total_seconds().astype(int)
print (df)
date new seconds
0 2017-05-02 00:00:00 2017-05-01 10:00:00 50400
1 2017-05-03 01:00:00 2017-05-02 10:00:00 54000
我有一个 pandas 数据框,其中包含以下格式的时间:
2017-05-02 00:00:00+00:00
2017-05-03 01:00:00+00:00
我想找出他们与前一天特定时间的区别,如上例:
2017-05-01 10:00:00
2017-05-02 10:00:00
我知道 timedelta 是解决方案,但我应该如何使用它?
使用 floor
,减去一天并在 Timedelata
秒内将 10 小时添加到从列 date
.
Series
日期
解决方案的优点是不需要创建辅助列然后删除它。
print (df)
date
0 2017-05-02 00:00:00+00:00
1 2017-05-03 01:00:00+00:00
#if necessary convert to datetime
df['date']= pd.to_datetime(df['date'])
dates = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (dates)
0 2017-05-01 10:00:00
1 2017-05-02 10:00:00
Name: date, dtype: datetime64[ns]
df['timedelta'] = df['date'] - dates
print (df)
date timedelta
0 2017-05-02 00:00:00 14:00:00
1 2017-05-03 01:00:00 15:00:00
对于 timedelata 的秒数,可以使用 total_seconds
and another solutions:
df['seconds'] = (df['date'] - dates).dt.total_seconds().astype(int)
print (df)
date seconds
0 2017-05-02 00:00:00 50400
1 2017-05-03 01:00:00 54000
相同的解决方案,如果还需要 new
列进行另一次处理,则只使用新列更好:
df['date']= pd.to_datetime(df['date'])
df['new'] = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (df)
date new
0 2017-05-02 00:00:00 2017-05-01 10:00:00
1 2017-05-03 01:00:00 2017-05-02 10:00:00
df['seconds'] = (df['date'] - df['new']).dt.total_seconds().astype(int)
print (df)
date new seconds
0 2017-05-02 00:00:00 2017-05-01 10:00:00 50400
1 2017-05-03 01:00:00 2017-05-02 10:00:00 54000