How add date to current date time Python

engrmahabub
Mahabubur Rahman
Published on Oct, 20 2023 1 min read 0 comments
image

I have created a helper function to get future or past day DateTime. 

def add_days_now_datetime(days=0):
    date_N_days_ago = datetime.datetime.now() + datetime.timedelta(days=days)
    return date_N_days_ago

 

Calling this function we can get current DateTime +/- DateTime.

Example :

datetime.datetime.now()
datetime.datetime(2021, 8, 30, 20, 2, 52, 827013)

 

So if we call the above function without passing any number we will get the same output.

add_days_now_datetime()
datetime.datetime(2021, 8, 30, 20, 4, 23, 582737)

 

We get the same output because by default value is 0.

Now if I want to get a 5-day future same time DateTime then - 

add_days_now_datetime(5)
datetime.datetime(2021, 9, 4, 20, 4, 53, 156255)

 

If we want to get past same time DateTime then - 

add_days_now_datetime(-5)
datetime.datetime(2021, 8, 25, 20, 5, 18, 427882)

 

0 Comments