Skip to content

Instantly share code, notes, and snippets.

@lokesh1729
Last active October 31, 2019 12:20
Show Gist options
  • Save lokesh1729/ab185a56dda9529a41be860c343b1fe6 to your computer and use it in GitHub Desktop.
Save lokesh1729/ab185a56dda9529a41be860c343b1fe6 to your computer and use it in GitHub Desktop.
This function returns the datetime object by substracting n months (time won't change) #python
def get_starting_date_minus_n_months(curr_date, num_months):
"""
Given the curr_date (datetime) object and num_months, returns the starting date
minus "num_months" months. Note that time won't change
for example: curr_date is "2019-10-22 23:59:59" and num_months is 3
it returns "2019-07-01 23:59:59"
"""
if num_months < 0:
raise ValueError(
"as the function name suggests it only supports for positive values of num_months"
)
number_of_years_to_travel_back = num_months // 12
calculated_year = curr_date.year - number_of_years_to_travel_back
calculated_month = (curr_date.month - num_months) % 12
if calculated_month == 0:
calculated_month = 12
if (
num_months > 0 # pylint: disable=R1716
and number_of_years_to_travel_back <= 0
): # special case : say if the curr_date month is 3 and num_months = 3, in that case we need to go a year back
calculated_year -= 1
elif calculated_month > curr_date.month:
calculated_year -= 1
return timezone.make_aware(
datetime.datetime(
calculated_year,
calculated_month,
1,
curr_date.hour,
curr_date.minute,
curr_date.second,
curr_date.microsecond if curr_date.microsecond else 0,
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment