Python月和日差异

时间:2016-12-01 02:06:22

标签: python

说我有两个日期:

  

2016-05-05和2016-08-10

我希望输出26(天)2(月)和10(天)

2016-05-05 - 2016-05-31 = 26 days

2016-06-01 - 2016-07-31 = 2 months

2016-08-01 - 2016-08-10 = 10 days

1 个答案:

答案 0 :(得分:0)

<% @cards.where.not(rarity: "Land").in_groups_of(6, false).each do |group| %>

输出:

from datetime import datetime

def months_between(date1,date2):
    if date1>date2:
        date1,date2=date2,date1
    m1=date1.year*12+date1.month
    m2=date2.year*12+date2.month
    months=m2-m1
    if date1.day>date2.day:
        months-=1
    elif date1.day==date2.day:
        seconds1=date1.hour*3600+date1.minute+date1.second
        seconds2=date2.hour*3600+date2.minute+date2.second
        if seconds1>seconds2:
            months-=1
    return months

date_format = "%Y-%m-%d"

date1 = "2016-05-05"
date2 = "2016-05-31"
date3 = "2016-06-01"
date4 = "2016-07-31"
date5 = "2016-08-01"
date6 = "2016-08-10"

date1_datetime = datetime.strptime(date1, date_format)
date2_datetime = datetime.strptime(date2, date_format)
date3_datetime = datetime.strptime(date3, date_format)
date4_datetime = datetime.strptime(date4, date_format)
date5_datetime = datetime.strptime(date5, date_format)
date6_datetime = datetime.strptime(date6, date_format)

difference1 = date2_datetime - date1_datetime
difference2 = months_between(date3_datetime, date4_datetime)
difference3 = date2_datetime - date1_datetime

print("%s - %s = %d days" % (date2, date1, difference1.days))
print("%s - %s = %d months" % (date3, date4, difference2))
print("%s - %s = %d days" % (date6, date5, difference3.days))

试试here!