I am given a date "12-31-2020" in string format, and I need to subtract 3 days, but I need the output "12-28-2020" in string format as well . I think I need to convert it to date format first in order to do subtraction. Can you help me what function I should use. Thanks in advance!
CodePudding user response:
Here's how to do it using only the datetime
module included the standard-library. The code first converts the string into a datetime.datetime
object, subtracts a 3 day timedelta
from it, and lastly prints out the result in the same format.
from datetime import datetime, timedelta
date_string = '31-12-2020'
date = datetime.strptime(date_string, '%d-%m-%Y') - timedelta(days=3)
print(date.strftime('%d-%m-%Y')) # -> 28-12-2020
CodePudding user response:
use a very powerful dateutil
lib from python. You can do almost any kind of fun with it.
from dateutil import parser, relativedelta
date_string = '31-12-2020'
print((parser.parse(date_string) - relativedelta.relativedelta(days=3)).strftime('%m-%d-%Y'))