English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básica de Python

Control de flujo en Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos en Python

Objetos y clases de Python

Fecha y hora de Python

Conocimientos avanzados de Python

Manual de referencia de Python

Fecha y hora actual en Python

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.

Example1:Obtener la fecha de hoy en Python

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.

Example2: Current date in different formats

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.

Example3: Get the current date and time

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.