Search code examples
pythonformatdatetime

How do I convert my date into a slightly different format


date = '9/4/2020'.

Now on excel I converted using the format TEXT(date,'YYYYMMDD'), how do I replicate the same in python?

I tried using the datetime function

d = datetime.strptime(date, '%Y%m%d')

but I get the value error ValueError: time data '9/4/2020' does not match format '%Y%m%d'

how do I fix this?


Solution

  • In Python this is called strptime (string parse time, ie get time object from a string) and strftime (string from time, get a string representation from a time object - the reverse process).

    The various time symbols are listed in the Python dcoumentation here. You need to describe the way the time is formatted exactly, including the separators (such as / or -). In between, you denote year, month,day, etc. according to the code in the docs. So in your case:

    d = datetime.strptime(date, '%d/%M/%Y')
    

    Would get you the time object, and then you could use

    print(datetime.strftime(d, '%Y%M%d'))
    

    to get the new one.

    Or in one line:

    d = strftime(strptime('9/4/2020', '%d/%M/%Y'), '%Y%M%d')
    

    should work. (Assuming day comes first.)