简体   繁体   English

Python:两个日期之间的月差

[英]Python: monthly difference between two dates

I have two date fields that I want to get the monthly difference on a 30-year loan term.我有两个日期字段,我想获得 30 年贷款期限的月差。 The dates are actually in yyyy-mm-dd format in my dataset, however, when I check the dtype in Python it says both are objects.在我的数据集中,日期实际上是 yyyy-mm-dd 格式,但是,当我检查 Python 中的 dtype 时,它说两者都是对象。 The sample data is below:样本数据如下:

|End Date  |StartDate|
|----------|---------|
|2/1/2018  |9/30/2016|
|1/1/2024  |9/30/2016|
|10/1/2023 |9/30/2016|
|4/1/2021  |9/30/2016|
|8/1/2030  |9/30/2016|
|10/1/2018 |9/30/2016|
|11/1/2016 |9/30/2016|
|7/1/2018  |9/30/2016|
|8/1/2020  |9/30/2016|
|2/1/2018  |9/30/2016|
|4/1/2018  |9/30/2016|

My code below works:我的以下代码有效:

diff = (pd.to_datetime(df['End Date'], format = '%Y-%m-%d') -  pd.to_datetime(df['Start Date'], format = '%Y-%m-%d'))/30

Huge BUT--the output looks like this:巨大的但是——output 看起来像这样:

16 days 07:12:00
88 days 07:12:00
85 days 05:36:00
54 days 19:12:00
168 days 10:24:00
24 days 08:48:00
1 days 01:36:00
21 days 07:12:00
46 days 16:48:00
16 days 07:12:00
18 days 06:24:00

How do I remove 'days' and everything after so only the value shows?如何删除“天”以及之后的所有内容,以便仅显示值? How do I convert the value to an integer?如何将值转换为 integer?

You just need diff.dt.days你只需要diff.dt.days

df = pd.DataFrame({
    'End Date': ['2/1/2018', '1/1/2024'], 
    'Start Date': ['9/30/2016', '9/30/2016'],
})

#the format = '%Y-%m-%d' doesn't match your example data (just letting pandas figure it out)
df['End Date'] = pd.to_datetime(df['End Date'])
df['Start Date'] = pd.to_datetime(df['Start Date'])

diff = (df['End Date']-df['Start Date'])/30
diff.dt.days

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

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