Skip to content

Instantly share code, notes, and snippets.

@openrijal
Last active November 10, 2016 10:24
Show Gist options
  • Save openrijal/4e2d3be9ca040309e2b70ca578b9ee90 to your computer and use it in GitHub Desktop.
Save openrijal/4e2d3be9ca040309e2b70ca578b9ee90 to your computer and use it in GitHub Desktop.
methods to calculate datetime from days, months and years delta in python
import datetime
def days_period_to_datetime(dd):
now = datetime.datetime.utcnow()
return now + datetime.timedelta(days=dd)
def months_period_to_datetime(mm):
now = datetime.datetime.utcnow()
new_day = now.day
month_sum = now.month + mm
if month_sum <= 12:
new_month = month_sum
else:
new_month = month_sum % 12
new_year = int(now.year + month_sum / 12)
try:
return now.replace(year=new_year, month=new_month, day=new_day)
except ValueError:
# Must be a month whose days are less than 31
if new_month == 2:
try:
return now.replace(year=new_year, month=new_month, day=29)
except ValueError: # Must be 28 days then
return now.replace(year=new_year, month=new_month, day=28)
if new_month in (4, 6, 9, 11):
return now.replace(year=new_year, month=new_month, day=30)
def years_period_to_datetime(yy):
now = datetime.datetime.utcnow()
try:
return now.replace(year=now.year + yy)
except ValueError:
# Must be 2/29 if it is an Exception!
assert now.month == 2 and now.day == 29
return now.replace(month=2, day=28, year=now.year + yy)
print days_period_to_datetime(44)
print days_period_to_datetime(0)
print months_period_to_datetime(5)
print months_period_to_datetime(18)
print years_period_to_datetime(1)
print years_period_to_datetime(17)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment