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

Tutorial Básico do Python

Controle de Fluxo do Python

Funções no Python

Tipos de Dados do Python

Operações de Arquivos do Python

Objetos e Classes do Python

Data e Hora do Python

Conhecimento Avançado do Python

Manual de Referência do Python

Data e Hora Atuais no Python

Neste artigo, você aprenderá como obter a data e o horário atual em Python. Também usaremos o método strftime() para formatar a data e o horário em diferentes formatos.

Você pode usar várias maneiras para obter a data atual. Usaremosdatetimea classe date do módulo para realizar esta tarefa.

Example1:Obtenção da data de hoje em Python

from datetime import date
today = date.today()
print("Hoje é a data:", 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 = ", 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.

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.