Format datetime easily#
Formatting datetime is a common task in Python and could be a daunting task for those new to Python. Especially when you need to format datetime in a specific way and looking at the documentation can be daunting for some. The exampple below shows how to format datetime in a specific way with the time.strftime()
method what can be complicated with due to all the extra lines.
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
Since the introduction of Python 3.6, there is a new way to format datetime with the f-string. This makes it easier to format datetime in a specific way. The example below shows how to format datetime in a specific way with the f-string.
from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}")
print(f"{now:%A, %B %d, %Y}")
Using the f-string makes it easier to format datetime in a specific way and makes it easier to read. This is a great way to simplify your code and make it more readable for you and others in the future.