使用不同日历年的日期时间比较日期

时间:2017-11-01 22:04:33

标签: python date datetime

如果我尝试比较表格中的日期"月份"年份不同,月份差异不正确。如果我比较2016年1月到2017年3月,月份差异将是3而不是14。当年度增加时,我可以将月份设置为0。

import datetime

month_names = ["January",   "February", "March",    "April",
           "May",       "June",     "July",     "August",
           "September", "October",  "November", "December"]

months = {name : (index + 1) for index, name in enumerate(month_names)}

current_month    = datetime.date.today().strftime('%B')
month_joined     = input("Please enter the month you joined: ")
month_difference = abs(months[current_month] - months[month_joined])

current_year = int(datetime.date.today().strftime('%Y'))
year_joined = int(input('Please enter the year you joined: '))

year_due = year_joined + 1

year_difference = current_year - year_due

月差异不会影响年份的差异。我已经尝试了一些解决方案来忽略月份差异的输入,并且每年投入12个月。我需要准确的月份差异。有任何想法吗?我很难过。

1 个答案:

答案 0 :(得分:1)

我不确定“将月份设为0”是什么意思,但您可以将year_difference * 12添加到month_difference以映射2017年3月到2016年1月。