Convert US date to EU

wordcloud

Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.

Problem

You and your friends are going to Europe! You have made plans to travel around Europe with your friends, but one thing you need to take into account so that everything goes according to play, is that the format of their date is different than from what is used in the United States. Your job is to convert all your dates from MM/DD/YYYY to DD/MM/YYYY.

Task:
Create a function that takes in a string containing a date that is in US format, and return a string of the same date converted to EU.

Input Format:
A string that contains a date formatting 11/19/2019 or November 19, 2019.

Output Format:
A string of the same date but in a different format: 19/11/2019.

Sample Input:
7/26/2019

Sample Output:
26/7/2019

Solution

Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.

In [1]:
import calendar
d=input()
if ',' in d:
    d=d.replace(',','').split(' ')
    d[0]=str(list(calendar.month_name).index(d[0]))
else:
    d=d.split('/')
d[0],d[1]=d[1],d[0]
print("/".join(d))
9/1/2021

Explanation

My approach (or the algorithm)

  1. Extract day, month and year from the input.
  2. Swap positions of day and month.
  3. Output in MM/DD/YYYY format.

The code

  • The input can be two formats. First differentiate between the two input formats. One format contains a "," and the other doesn't.
  • If the input in the format November 19, 2019, then remove the comma and read into a list by splitting by space. Then convert November to 11 using calendar module.
  • If the input is in 11/19/2019 format, then split by "/" and read into a list.
  • Juxtapose day and month d[0],d[1]=d[1],d[0]
  • Convert list to a string in MM/DD/YYYY format using "/".join(d) and print it.

The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.

Last updated 2021-01-09 14:00:22.063044 IST

Comments