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.