-1

Complete the following function that converts a US date to a European date. Days and months are padded (if necessary) to become two digits each.

Example: europeanize('4/7/14') returns '07/04/12'

Example: europeanize('02/27/08') returns '27/02/08'

This is what I have so far. I am trying to get the current date to return a European date. Am I on the right track?

import datetime

today = datetime.date.today()
european_date = "2/12/2020"
def europeanize(date):
    if today == european_date:
        return european_date

print(today.strftime("%d/%m/%Y"))
Robert
  • 7,394
  • 40
  • 45
  • 64
  • 1
    You've got the right idea that you need to leverage `datetime` and `strftime()`. Assuming that you want the input and output of the function to be strings, think about converting the input string to a datetime object and then back into a string. – Harrison Totty Dec 02 '20 at 20:56
  • How do I do that? – Courtney Mills Dec 02 '20 at 20:59
  • 1
    This related question might contain the answers you're looking for: https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format – Harrison Totty Dec 02 '20 at 21:09
  • 2
    Does this answer your question? [Parse date string and change format](https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format) – Pranav Hosangadi Dec 02 '20 at 21:29

1 Answers1

1

Here's a simple solution.

from datetime import datetime 

def europeanize(date):
    european_date = datetime.strptime(date, '%m/%d/%y').strftime("%d/%m/%y")
    return european_date
    
       
print(europeanize('11/9/14'))

datetime.strptime(date, '%m/%d/%y') converts the American date string to a datetime object which can then be manipulated as you wish into a string with strftime

Skygear
  • 90
  • 6
  • @CourtneyMills Tested it and seems to run fine make sure you have datetime module installed. – Crapy Dec 02 '20 at 21:30
  • The website I’m running it off of does not have the date time module installed. It only takes like import date time etc... – Courtney Mills Dec 02 '20 at 21:40
  • @CourtneyMills Then you need to change `datetime.strptime(date, '%m/%d/%y')` to `datetime.datetime.strptime(date, '%m/%d/%y')`. This means that you will now go to the `datetime` module and then get the rest. – Skygear Dec 02 '20 at 21:50
  • "NotImplementedError: _strptime is not yet implemented in Skulpt on line 1" I get this error when I run the code – Courtney Mills Dec 02 '20 at 21:58
  • import datetime def europeanize(date): european_date = datetime.datetime.strptime(date, '%m/%d/%y') return european_date print(europeanize('11/9/14')) – Courtney Mills Dec 02 '20 at 21:58
  • @CourtneyMills You might want to change platforms at this point. Try it in repl.it. – Skygear Dec 02 '20 at 22:07
  • What if dates are in list, how to convert them at once, I tried a lot, still unable to convert. – Display Name is missing Oct 28 '22 at 15:58