0

`what is the index of the second "/" in a date.

  date = input('write todays date: ')
  i  = date.find('/')

  month = date\[:i]
  day =??????
  year = ???????
  print(f' todays month is {month}')

I tried all my knowledge did not work`

Hasan
  • 1
  • 6
    I recommend using a proper date library rather than handling the parsing yourself. e.g. you could use `datetime.datetime.strptime(date, '%m/%d/%Y')` – 0x5453 Jan 19 '23 at 15:54
  • I agree with @0x5453. I you want to know how to work with strings you can also do : `month, day, year = date.split("/")` Otherwise, to answer directly to your question the index of the second "/" si 5 – Maxime Lavaud Jan 19 '23 at 15:56
  • 1
    you could also use `date.split('/')` which will give you a list and you just index into the elements that you want – Andrew Ryan Jan 19 '23 at 15:56
  • 1
    Does this answer your question? [Find the nth occurrence of substring in a string](https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string) Also see [How can I convert a string into a date object and get year, month and day separately?](https://stackoverflow.com/questions/12430287/how-can-i-convert-a-string-into-a-date-object-and-get-year-month-and-day-separa) – Abdul Aziz Barkat Jan 19 '23 at 15:58

3 Answers3

2

I would suggest you use datetime to perform parsing and formatting, in this case using datetime.strptime

>>> from datetime import datetime
>>> dt = datetime.strptime('12/25/2009', '%m/%d/%Y')
>>> dt
datetime.datetime(2009, 12, 25, 0, 0)
>>> dt.month, dt.day, dt.year
(12, 25, 2009)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

The Python method find takes optional arguments. You can pass the start index to look for. In your case the start would be the end index of the first match.

Example:

first = date_str.find("/")
if (first == -1):
     # not found
second = date_str.find("/", first + 1)
...
Jib
  • 1,334
  • 1
  • 2
  • 12
-1

If I am understanding your question correctly, the second "/" in that date format would be index 2 if you were looking at that string as a zero based array.

So I say... 2

Bellarose143
  • 165
  • 1
  • 11