Python F-String formatting for date like String

Viewed 834

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

Thanks - Faded

2 Answers

The error message is because your data is strings not datetimes, and the format specifier :%Y.%m.%d only works with datetimes. You can parse your strings into datetimes using strptime() but since you just want to reverse the order, you can just do:

>>> data = '25.02.2021'
>>> '{}.{}.{}'.format(*reversed(data.split(".")))
'2021.02.25'

There are other ways to do this but you seemed to want to do it using string formatting.

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

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