I am trying to solve a problem where i need to find difference of number months between 2 strings
"January 2022"
"July 2022"
Answer=7
I looked all over internet to find answer but could not, mostly answer used datetime library
Is there any other way to solve this problem?
I tried to create a static dictionary like this but could not proceed further
m={
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
CodePudding user response:
At first I tried to use datetime
modules but later if found much simpler way.
- you reverse the dictionary to convert month to month id
- convert year to month by mulitplying with 12.
month_ids = dict({
"January":1,
"February":2,
"March":3,
"April":4,
"May":5,
"June":6,
"July":7,
"August":8,
"September":9,
"October":10,
"November":11,
"December":12
})
def to_months(month_year):
month_name, year = month_year.strip().split()
return (int(year) * 12) month_ids[month_name.strip()]
print(to_months("July 2022") - to_months("January 2022"))
Note: As per above logic, the difference b/w July/January comes as 6 as this code does not include last month into count. As per your need, you can include 1 if need.
CodePudding user response:
Use dateutil
:
from dateutil import parser, relativedelta
def delta_months(a, b):
""" returns negative delta if b > a """
a = parser.parse(a)
b = parser.parse(b)
delta = relativedelta.relativedelta(a, b)
delta = delta.years * 12 delta.months
return delta
a = 'January 2022'
b = 'March 2022'
print(delta_months(a, b)) # -2
print(delta_months(b, a)) # 2