1

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.

backlog
  • 55
  • 12
  • 2
    Learn python strings. – TomServo Jul 17 '21 at 21:41
  • @TomServo kindly give me a possible solution, I have to loop thousands of time – backlog Jul 17 '21 at 21:41
  • @backloggiash well this is basic python string formatting, if You know loops You should also know how to format strings, I suggest You look into [`f strings`](https://realpython.com/python-f-strings/) – Matiiss Jul 17 '21 at 21:48
  • 2
    Your question is unclear and shows lack of research effort. You've shown no attempt to solve the problem. If you want to modify a string like that URL, then learn to modify strings in python. – TomServo Jul 17 '21 at 21:48
  • I solved using `'-'.join(url.split('-')[:-1] + [str(int(url.split('-')[-1]) -1 )] )` – backlog Jul 17 '21 at 21:57

6 Answers6

4

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}')
3

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))
Ben Alan
  • 1,399
  • 1
  • 11
  • 27
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)
Jonathan
  • 76
  • 7
1

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)
pakpe
  • 5,391
  • 2
  • 8
  • 23
  • I already mentioned that this simple solution assumes that the date is greater than 01. Otherwise, you can resort to the datetime solution. – pakpe Jul 17 '21 at 22:04
  • Yes, sorry, I've missed that part (I've just removed the comment). – Timus Jul 17 '21 at 22:05
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")
0

I have solved this using:

'-'.join(url.split('-')[:-1] + [str(int(url.split('-')[-1]) -1 )] )
backlog
  • 55
  • 12