Calculating the date a fixed number of days from given date

Question:

I need to design a code that will automatically generate the date X number of days from current date.

For that, I currently have a function that returns an epoch timestamp, which I then add the fixed number of days in seconds. However, I am currently stuck there and do not know how to convert the epoch timestamp into a Gregorian calendar date format (DD/MM/YYYY HH:MM). Displaying time is optional, can be rounded to the nearest day.

A way to do this without using an epoch timestamp and directly getting the current date in a readable format, printing it, and adding X days to it before generating the second date, is also fine, but I have no idea how that would work.

Any help/input would be much appreciated. Thanks in advance.

Asked By: Terrornado

||

Answers:

You can use timedelta.

import datetime as dt

x = 5  # Days offset.
now = dt.datetime.now()
>>> now + dt.timedelta(days=x)
datetime.datetime(2017, 12, 2, 21, 10, 19, 290884)

Or just using days:

today = dt.date.today()
>>> today + dt.timedelta(days=x)
datetime.date(2017, 12, 2)

Easy enough to convert back to a string using strftime:

>>> (today + dt.timedelta(days=x)).strftime('%Y-%m-%d')
'2017-12-02'
Answered By: Alexander
import datetime
x = 5
'''
Date_Time = datetime.datetime.now()#It wil give Date & time both

Time = datetime.datetime.now().time()#It will give Time Only
'''

Date = datetime.datetime.now().date()#It will give date only


print(Date + datetime.timedelta(days=x))#It will add days to current date

Output:

2017-12-03
Answered By: sachin dubey