Formatting dates in Python using f-strings
May 27, 2022
How many times have you struggled trying to properly format datetimes in Python?
I can say it for you, but I really struggled on this in the past.
That’s right! In the past!!
I’ve discovered a way to format dates in Python using just f-strings. If you are not familiar with f-strings, you should! It’s a awesome way to format strings in Python. It's not only in "prints" as you can use it anywhere strings and variables are involved. To know more: https://docs.python.org/3/tutorial/inputoutput.html
Let me show you an example:
from datetime import datetimedate = datetime(2022, 5, 27, 11, 44)print(f'Your appointment is schedule to start at {date:%I:%M %p} on {date:%Y-%m-%d}.', 'Be there!', sep='\n')
The results will be like:
Your appointment is schedule to start at 11:44 AM on 2022-05-27.
Be there!
Awesome, right?!