Search code examples
pythonformatf-string

Python F-String formatting for date like String


I wanted to use F-Strings that Python 3.8 provides to Format a string the way I would like to.

The original String/Strings look like this:

25.02.2021
17.02.2021
17.02.2021
17.02.2021
11.03.2021
17.02.2021
17.02.2021
04.03.2021

Now I want to change them the "other way around" so I want them to look like this: 2021.03.12 So YYYY.MM.DD

I have tried: line = f'{line:%Y.%m.%d}' line is the original Stringname.

But if I use this I get this error:

    line = f'{line:%Y.%m.%d}'
ValueError: Invalid format specifier

Solution

  • You can try splitting it with . and then join by reversing it. This is simple solution

    line = '.'.join(line.split('.')[::-1])