One way to obtain the current date and time in Python is by using the date
class from the date
module.
An example of displaying the current date in Python:
from datetime import date
today = date.today()
print("Today's date:", today)
Output:
Today's date: 2024-05-11
We imported the date
class from the date
module. Then, we used the date.today()
method to get the current local date.
An example of displaying the current date in different formats in Python:
from datetime import date
today = date.today()
# Format dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)
# Month in text format, day, and year
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)
# Format mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)
# Month abbreviated, day, and year
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)
Output:
d1 = 11/05/2024
d2 = May 11, 2024
d3 = 05/11/24
d4 = May-11-2024
Getting the current date and time in Python:
If we need to get the current date and time, we can use the datetime
class from the datetime
module. For example:
from datetime import datetime
# Datetime object containing the current date and time
now = datetime.now()
print("now =", now)
# Format dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Output:
now = 2024-05-11 11:27:49.796890
date and time = 11/05/2024 11:27:49
We used the datetime.now()
method to get the current date and time. Then, we used the strftime()
method to present the date and time in a different format.