English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to use Python to get today's date and the current date and time. We will also use the strftime() method to format the date and time in different formats.
There are multiple ways to get the current date. We will usedatetimethe date class of the module to complete this task.
from datetime import date today = date.today() print("Today's date:", today)
Output result:
Today's date: 2020-04-13
Here, we import the date class from the datetime module. Then, we use the date.today() method to get the current local date.
By the way, date.today() returns a date object, which is assigned toTodayvariable. Now, you can usestrftime()Method creates a string representing the date in a different format.
from datetime import date today = date.today() # dd/mm/YY d1 = today.strftime("%d/%m/%Y print("d1 =", d1) # Textual month, day, and year d2 = today.strftime("%B %d, %Y" print("d2 =", d2) # mm/dd/y d3 = today.strftime("%m/%d/%y print("d3 =", d3) # Abbreviation of the month, date, and year d4 = today.strftime("%b-%d-%Y print("d4 =", d4)
When you run the program, the output will be similar to:
d1 = 16/09/2019 d2 = September 16, 2019 d3 = 09/16/19 d4 = Sep-16-2019
If you need to get the current date and time, you can use the datetime module's datetime class.
from datetime import datetime # datetime object containing the current date and time now = datetime.now() print("now =", now) # dd/mm/YY H:M:S dt_string = now.strftime("%d/%m/%Y %H:%M:%S) print("date and time =", dt_string)
Here, we are accustomed to using datetime.now() to get the current date and time. Then, we use strftime() to create a string representing the date and time in a different format.