Borislav Hadzhiev
Last updated: Jun 22, 2022
Photo from Unsplash
To add days to the current date in Python:
datetime.now()
method to get the current local date and time.timedelta
object by passing the number of days to the timedelta
class.timedelta
object.from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2022-06-22 18:48:12.336278 result = now + timedelta(days=7) print(result) # 👉️ 2022-06-29 18:48:12.336278 print(result.date()) # 👉️ 2022-06-29 print(f'{result:%Y-%m-%d %H:%M:%S}') # 👉️ 2022-06-29 18:48:12
Make sure to import the datetime
and
timedelta
classes from the datetime
module.
We used the datetime.now method to get the current local date and time.
now
variable stores a datetime
object, to which we can add days using the timedelta
class.The timedelta
class can be passed the days
, weeks
, hours
, minutes
,
seconds
, milliseconds
and microseconds
as arguments.
All of the arguments are optional and default to 0
.
It's best to only use keyword arguments in a call to the timedelta
class as
the order of arguments can be confusing.
We only provided a value for the days
argument in the example.
If you only need to extract the date after the operation, call the date()
method on the datetime
object.
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2022-06-22 18:55:39.055210 result = now + timedelta(days=5) print(result) # 👉️ 2022-06-27 18:55:39.055210 print(result.date()) # 👉️ 2022-06-27
The datetime.date method returns a date object with the same year, month and day.
If you need to format the date in a certain way, use a formatted string literal.
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2022-06-22 19:00:32.391298 result = now + timedelta(days=6) print(result) # 👉️ 2022-06-28 19:00:32.391298 print(result.date()) # 👉️ 2022-06-28 print(f'{result:%Y-%m-%d %H:%M:%S}') # 👉️ 2022-06-28 19:00:32
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
Make sure to wrap expressions in curly braces - {expression}
.
Formatted string literals also enable us to use the format specific mini-language in expression blocks.