减去两个datetime以获取天数(python) [英] Subtract two datetime to get the number of days (python)

查看:691
本文介绍了减去两个datetime以获取天数(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的两天里,我一直在思考这个问题,而我正处于放弃的边缘。

I have been wrapping my mind around this for the last two days, and I am on the verge of giving up.

我有一个名为 Renewed_subscription 的列,格式为 datetime 。我需要确定从今天到一个人必须续订订阅的日期之间有多少天。

I have a col named Renewed_subscription, format datetime. I need to get how many days are between today and the date when a person has to renew his subscription.

from datetime import datetime
dataset['DaysUntilSub'] = dataset.apply(lambda x: (pd.Timestamp.today().strftime('%Y-%m-%d') - str(dataset['Renewed_subscription'])).days, axis=1)

它抛出错误:


TypeError跟踪(最近一次通话)

TypeError Traceback (most recent call last)

C:\Report.py in()

C:\Report.py in ()

-> 166数据集['DaysUntilSub'] =数据集.apply(lambda x:(pd.Timestamp.today()。strftime('%Y-%m-%d ')-str(dataset ['Renewed_subscription'])。days,axis = 1)

--> 166 dataset['DaysUntilSub'] = dataset.apply(lambda x: (pd.Timestamp.today().strftime('%Y-%m-%d') - str(dataset['Renewed_subscription'])).days, axis=1)

168 #dataset ['DaysUntilSub'] = dataset.apply(lambda x :(pd.Timestamp.today()。strftime('%Y-%m-%d')-str(dataset ['Renewed_subscription']))。days,axis = 1)

168 #dataset['DaysUntilSub'] = dataset.apply(lambda x: (pd.Timestamp.today().strftime('%Y-%m-%d') - str(dataset['Renewed_subscription'])).days, axis=1)

C:\用户\katep\Anaconda3\lib\站点包\pandas\core\frame.py in apply(self,func,axis,broa dcast,raw,reduce,args,** kwds)

C:\Users\katep\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)

4150如果reduce为None:
4151 reduce = True
-> 4152 return self ._apply_standard(f,axis,reduce = reduce)
4153 else:
4154 return self._apply_broadcast(f,axis)

4150 if reduce is None: 4151 reduce = True -> 4152 return self._apply_standard(f, axis, reduce=reduce) 4153 else: 4154 return self._apply_broadcast(f, axis)

C:\ \用户\katep\Anaconda3\lib站点包\熊猫\核心\frame.py in _apply_standard(自我,函数,轴,ignore_failures,reduce)

C:\Users\katep\Anaconda3\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)

4246尝试:

4247 for i,v in enumerate(series_gen):

4247 for i, v in enumerate(series_gen):

- > 4248个结果[i] = func(v)

-> 4248 results[i] = func(v)

4249 keys.append(v.name)

4249 keys.append(v.name)

4250例外,例如e:

4250 except Exception as e:

C:\Report.py in(x)

C:\Report.py in (x)

TypeError:( -的不支持的操作数类型:'str'和'str',出现在索引42')

TypeError: ("unsupported operand type(s) for -: 'str' and 'str'", 'occurred at index 42')

如果您能指出我的错误,我将不胜感激,因为我不能因此而继续分析!

I will be very grateful if you could, please, point at my error, because I cannot proceed with the analysis because of it!

推荐答案

如上所述,您不想在减去之前将 datetime 转换为字符串。您可以使用简单的-符号进行操作,然后查找多少

As above mentioned, you don't want to cast datetime to string before subtraction. You can operate using simple - sign and find how many days later.

from datetime import datetime
import pandas as pd

# create example dataframe
df = pd.DataFrame([datetime(1985, 4, 10), 
                   datetime(2010, 4, 10), 
                   datetime(2015, 4, 10), 
                   datetime(2017, 4, 10)], columns=['Renewed_subscription'])
# subtraction with today
df['DaysUntilSub'] = df['Renewed_subscription'].map(lambda x: (datetime.today() - x).days)

数据帧溢出

  Renewed_subscription  DaysUntilSub
0   1985-04-10  11695
1   2010-04-10  2564
2   2015-04-10  738
3   2017-04-10  7

同样的解决方案没有lambda:

And the same solution without a lambda:

def days_from_today(date):
    return (datetime.today() - date).days

df['DaysUntilSub'] = df['Renewed_subscription'].map(days_from_today)

这篇关于减去两个datetime以获取天数(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆