简体   繁体   English

Pandas-将默认日期时间更改为另一个时间

[英]Pandas- Change default datetime to another time

I have a dataframe which has two datetime columns.我有一个数据框,它有两个datetime时间列。 I am doing difference of those two datetime columns to find number of days between them.我正在对这两个datetime时间列进行差异以查找它们之间的天数。 The problem is the time in both of them starts from 06:00:00 so when the actual day gets over, the difference remains the same.问题是它们的时间都是从06:00:00开始的,所以当实际一天结束时,差异保持不变。

Here is the dataframe这是数据框

machineID   datetime_tel    comp1     datetime_maint    sincelastComp1
30       2021-01-01 23:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 00:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 01:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 02:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 03:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 04:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 05:00:00    1   2020-07-31 06:00:00 154
30       2021-01-02 06:00:00    1   2020-07-31 06:00:00 155
30       2021-01-02 07:00:00    1   2020-07-31 06:00:00 155

Here you can see when we have date as 2021-01-02 and time as 00:00:00 , there is no increment in sincelastComp1 (ideally it should have been incremented as date as increased by 1).在这里你可以看到当我们的日期为2021-01-02和时间为00:00:00时, sincelastComp1没有增量(理想​​情况下,它应该随着日期的增加而增加 1)。 It is only increasing when time is 06:00:00 .它仅在时间为06:00:00时增加。

I want the increment to happen when the date changes.我希望在日期更改时发生增量。

if I understand you right, you want to calculate the difference between dates and not between timestamps:如果我理解正确,您想计算日期之间的差异,而不是时间戳之间的差异:

df['sincelastComp1'] = (df['datetime_tel'].apply(pd.Timestamp).dt.date -
                        df['datetime_maint'].apply(pd.Timestamp).dt.date).dt.days

output:输出:

    machineID         datetime_tel  comp1       datetime_maint  sincelastComp1
0         30  2021-01-01 23:00:00      1  2020-07-31 06:00:00             154
1         30  2021-01-02 00:00:00      1  2020-07-31 06:00:00             155
2         30  2021-01-02 01:00:00      1  2020-07-31 06:00:00             155
3         30  2021-01-02 02:00:00      1  2020-07-31 06:00:00             155
4         30  2021-01-02 03:00:00      1  2020-07-31 06:00:00             155
5         30  2021-01-02 04:00:00      1  2020-07-31 06:00:00             155
6         30  2021-01-02 05:00:00      1  2020-07-31 06:00:00             155
7         30  2021-01-02 06:00:00      1  2020-07-31 06:00:00             155
8         30  2021-01-02 07:00:00      1  2020-07-31 06:00:00             155

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM