Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading