0

How can I create a function in Python that takes a datetime object and an integer as inputs, and returns a new datetime object with the desired offset?

I tried before with this:

from datetime import datetime, timedelta

def get_offset_datetime(source_date_time, month_offset):
    year, month, day = (source_date_time.year + month_offset // 12,
                       source_date_time.month + month_offset % 12,
                       source_date_time.day)
    if month>12:
        year+=1
        month-=12
    elif month<1:
        year-=1
        month+=12
    offset_datetime = datetime(year, month, day, source_date_time.hour, source_date_time.minute, source_date_time.second)
    return offset_datetime

but it raise error for some dates. for example:

source_date_time = datetime(2022,1,31)
month_offset = 1
offset_datetime = get_offset_datetime(source_date_time, month_offset)
print(source_date_time)
print(offset_datetime)

I expected the code print this:

2022-02-28 00:00:00

but i got this error:

Traceback (most recent call last):
  File "/home/user/Desktop/exam/main.py", line 42, in <module>
    offset_datetime = get_offset_datetime2(source_date_time, month_offset)
  File "/home/user/Desktop/exam/main.py", line 27, in get_offset_datetime2
    offset_datetime = datetime(year, month, day, source_date_time.hour, source_date_time.minute, source_date_time.second)
ValueError: day is out of range for month

please give me another clean code for doing this task.

Hossein Vejdani
  • 961
  • 8
  • 19

1 Answers1

0

I found the right answer! Here is a Python function that takes a source_date_time as a datetime object and an month_offset as an integer, and returns a new datetime object with the desired offset:

from datetime import timedelta
from dateutil.relativedelta import relativedelta

def get_offset_datetime(source_date_time, month_offset):
    offset_datetime = source_date_time + relativedelta(months=month_offset)
    return offset_datetime

You can call the function like this:

from datetime import datetime

source_date_time = datetime.now()
month_offset = 2

offset_datetime = get_offset_datetime(source_date_time, month_offset)
print(offset_datetime)

This will print the datetime 2 months ahead of the current date and time. It is the best and accurate way to calculate the offset and it is using dateutil library which handles leap years, days at end of month and other edge cases.

Hossein Vejdani
  • 961
  • 8
  • 19
  • sure, it is similar. but in my case i consider month offset, i think there is a more complexity! – Hossein Vejdani Jan 19 '23 at 06:29
  • You didn't answer the question about how to handle the variable size of a month. You just picked one library that arbitrarily picked one method. But yes, always use a library for dates. – Kenny Ostrom Jan 19 '23 at 06:33