English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet article, vous apprendrez à obtenir la date et l'heure actuelle en Python. Nous utiliserons également la méthode strftime() pour formater la date et l'heure de différentes manières.
Vous pouvez utiliser plusieurs méthodes pour obtenir la date actuelle. Nous utiliseronsdatetimepar le module date pour accomplir cette tâche.
from datetime import date today = date.today() print("La date d'aujourd'hui:", 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()methods to create 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) # Written 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 HH:MM:SS 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.