I have a string
url = 'https://www.xyz/2020-12-22'
I want to change this url variable to 'https://www.xyz/2020-12-21' (Means subtaction one from only date value). How can I do that ? Thanks in advance.
I have a string
url = 'https://www.xyz/2020-12-22'
I want to change this url variable to 'https://www.xyz/2020-12-21' (Means subtaction one from only date value). How can I do that ? Thanks in advance.
Use a regular expression to catch the date inside the string. Convert it to datetime, then subtract a day using datetime.timedelta()
. Use an f-string to join the new date and the url.
from datetime import timedelta, datetime
import re
url = 'https://www.xyz/2020-12-22'
date = re.findall(r"[\d]{4}-[\d]{2}-[\d]{2}", url)
date = datetime.strptime(date[0], "%Y-%m-%d")
date = date - timedelta(1)
date = date.date()
print(date)
print(f'https://www.xyz/{date}')
You can use the datetime module
from datetime import date, timedelta
url = 'https://www.xyz/2020-12-22'
#take slice of url that represents the date
dateString = url[-10:]
#convert string to date object
d = date.fromisoformat(dateString)
#subtract 1 day
url = 'https://www.xyz/' + str(d - timedelta(days=1))
Hey I made a little solution I know it's not the best but maybe it helps you
url = 'https://www.xyz/2020-12-22'
date = url.split("-")
result = int(date[2]) -1
new_url = date[0] + "-" + date[1] + "-" + str(result)
print(new_url)
Here is a simple one-liner solution. It assumes that your date is greater that 01.
new_url = url[:-2] + str(int(url[-2:])-1)
from datetime import datetime, timedelta
url = 'https://www.xyz/2020-12-22'
url_parts = url.rsplit('/', 1)
url = url_parts[0] + (datetime.fromisoformat(url_parts[1]) + timedelta(days=1)).strftime("/%Y-%m-%d")
I have solved this using:
'-'.join(url.split('-')[:-1] + [str(int(url.split('-')[-1]) -1 )] )