i have seen some threats about this already but im not quite sure how to do mine. i have a string date (DD/MM/YY) then i need to subtract the day by 2 and i need to change it to (MM/DD/YY). For example, if i have a string of 01/04/2021, i need the final output to be 03/30/2021. i have tried using datetime.date but it seems like i cannot put a string of 01/04/2021 in it. Any helps? Here is what i got so far, but it doesn’t really work i don’t quite understand datetime library so its a little bit confusing, sorry in advance.
import datetime as dt from dateutil.relativedelta import relativedelta date_1 = '01/04/2021' date_2 = list(date_1) date_2[0:2], date_2[3:5] = date_2[3:5], date_2[0:2] date_2 = ''.join(date_2) # change date_1 to MM/DD/YY print(dt.date(int(date_2[0:4]),int(date_2[5:7]), int(date_2[8:10])) - relativedelta(days=2)) # i tried to minus the day out, but the code fails, #Here is the error, in case it helps, ValueError: invalid literal for int() with base 10: '04/0'
Answer
You can use timedelta
, strptime
and strftime
.
from datetime import datetime from datetime import timedelta d = '01/04/2021' print((datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)).strftime('%m/%d/%y')) #03/30/21
Explanation
datetime.strptime
: This function allows you to take a string
, provide the formatting and return a datetime
object.
datetime.strptime(d, '%d/%m/%Y') datetime.datetime(2021, 4, 1, 0, 0)
datetime.timedelta
: Allows us to add and subtract time on a datetime
object.
datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2) datetime.datetime(2021, 3, 30, 0, 0)
datetime.strftime
: Allows us to format our datetime object as a string
in the format we specify
datetime(2021, 3, 30, 0, 0).strftime('%m/%d/%y') '03/30/21'
Joining these all together, we can convert your string
to a date
, make the change to the date
that we want, and then convert it back to a string
.