I have a method which returns the date as "August 12, 2022" how can change that to datetime to concatenate with datetime.timedelta(days = 10)
def date_return():
return date
date_return() + datetime.timedelta(days=10)
throws TypeError: unsupported operand type(s) for -: ‘str’ and ‘datetime.timedelta’
>Solution :
You need to convert the string into a datetime object. Python doesn’t know any information about the date since it is a string.
>>> import datetime
>>> datetime.datetime.strptime('August 12, 2022', '%B %d, %Y')
datetime.datetime(2022, 8, 12, 0, 0)
>>> datetime.datetime.strptime('August 12, 2022', '%B %d, %Y') + datetime.timedelta(days=10)
datetime.datetime(2022, 8, 22, 0, 0)
datetime string format codes for your date:
%B Full month name. January, February,...
%d Day of the month as a zero-padded decimal. 01, 02, ..., 31
%Y Year with century as a decimal number. 2013, 2019 etc.
date_return() returns a string so you can just use it in place of the hardcoded string above:
datetime.datetime.strptime(date_return(), '%B %d, %Y') + datetime.timedelta(days=10)