How add date to current date time Python

Published 2 days ago5 min read4 comments

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)
2 Comments

K.R. NooR Feb 14, 2023 - 05:10 AM
Mahabubur Rahman Mar 14, 2023 - 06:56 PM