0

I have a string that comes in the format name = "1/2/2021", how can I convert this string to the format newName = "2021-2-1"

original =  name
day = original[0]
month = original[2]
year = original[4:8]
combination = year + "-" + month + "-" + day

I have tried using this but brings wrong values when date or month changes to more than 2 characters

Johnn Kaita
  • 432
  • 1
  • 3
  • 13
  • 1
    Import datetime and convert it. Also Stack Overflow has so many examples of this already https://stackabuse.com/converting-strings-to-datetime-in-python/ – Joe Ferndz Jan 03 '21 at 02:33

3 Answers3

0

without using date/time functions:

n1 = name.split("/")
print(f"{n1[2]}-{n1[1]}-{n1[0]}")
ktp
  • 126
  • 8
0
new = original.split("/")[2]+"-"+original.split("/")[1]+"-"+original.split("/")[0]
Synthase
  • 5,849
  • 2
  • 12
  • 34
  • Add some explanation to your code please. It's understandable, but it will be better to add some description – ppwater Jan 03 '21 at 05:24
0

Passing string and delimiter as "/" also works without datetime.

def splitStrings(st, dl):
    word = ""
    st += dl
    l = len(st)
    substr_list = []
    for i in range(l):
        if (st[i] != dl):
            word += st[i]
        else:
            if (len(word) != 0):
                substr_list.append(word)
            word = ""
    return substr_list


def getCutDate(self, string):
    out = (splitStrings(string, '/'))
    day = out[0]
    month = out[1]
    year = out[2][0:4]
    result = year + "-" + month + "-" + day
    return result
Johnn Kaita
  • 432
  • 1
  • 3
  • 13