Home > OS >  Why doesn't it work code for changing date format from 'MM/DD/YYYY' to 'YYYYMMDD
Why doesn't it work code for changing date format from 'MM/DD/YYYY' to 'YYYYMMDD

Time:04-16

I want to change date format from 'MM/DD/YYYY' to 'YYYYMMDD'. But my code makes date format from 'MM/DD/YYYY' to 'MMYYYYDD'.

input_date = input("DATE(MM/DD/YYYY): ")

list_splited_date = input_date.split("/")
yy = list_splited_date.pop(2)
modified_date = yy.join(list_splited_date)

print(f"\"{input_date}\" -> \"{modified_date}\"")

Below is a execution result example.

DATE(MM/DD/YYYY): 04/16/2022
"04/16/2022" -> "04202216"

What's the problem??

CodePudding user response:

This:

 yy.join(list_splited_date)

means to join the pieces with yy as a separator. In general it joins: i0 sep i1 sep i2 sep i3 sep .... iN.

In this case the list contains only MM, DD, so you get MM YYYY DD.

A simple code works fine:

split_date = input_date.split("/")
modified_date = split_date[2]   split_date[0]   split_date[1]

CodePudding user response:

Using yy.join(list_splited_date) joins the elements in list_splited_date (which are MM and DD) by using the the separator yy (which is YYYY) between them, and not, as you might have thought, by simply concatenating yy with the contents of list_splited_date.

input_date = input("DATE(MM/DD/YYYY): ")
MM, DD, YYYY = input_date.split('/')
modified_date = f'{YYYY}/{MM}/{DD}'
print(f"\"{input_date}\" -> \"{modified_date}\"")
  • Related