English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este artículo, aprenderá cómo obtener la fecha y la hora actual en Python. También utilizaremos el método strftime() para formatear la fecha y la hora en diferentes formatos.
Puede adoptar varias formas para obtener la fecha actual. Vamos a usardatetimela clase date del módulo para completar esta tarea.
from datetime import date today = date.today() print("La fecha de hoy:", 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()The 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 = "1) # Textual month, day, and year d2 = today.strftime("%B %d, %Y") print("d2 = "2) # mm/dd/y d3 = today.strftime("%m/%d/%y print("d3 = "3) # Abbreviation of the month, date, and year d4 = today.strftime("%b-%d-%Y print("d4 = "4)
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.