Neste artigo, você aprenderá a manipular data e hora em Python com a ajuda de exemplos.
Python tem um módulo denominado datetime para trabalhar com datas e horas. Vamos criar alguns programas simples relacionados a data e hora antes de nos aprofundarmos.
Exemplo 1: Obter data e hora atuais
import datetime datetime_object = datetime.datetime.now() print(datetime_object)
Quando você executa o programa, a saída será algo como:
19/12/2018 09: 26: 03.478039
Aqui, importamos o módulo datetime usando a import datetime
instrução.
Uma das classes definidas no datetime
módulo é datetime
class. Em seguida, usamos o now()
método para criar um datetime
objeto contendo a data e hora locais atuais.
Exemplo 2: Obter Data Atual
import datetime date_object = datetime.date.today() print(date_object)
Quando você executa o programa, a saída será algo como:
19/12/2018
Neste programa, usamos o today()
método definido na date
classe para obter um date
objeto contendo a data local atual.
O que há dentro do datetime?
Podemos usar a função dir () para obter uma lista contendo todos os atributos de um módulo.
import datetime print(dir(datetime))
Quando você executa o programa, a saída será:
('MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', ' datetime ',' datetime_CAPI ',' time ',' timedelta ',' timezone ',' tzinfo ')
As classes comumente usadas no módulo datetime são:
- data aula
- hora da aula
- classe datetime
- classe timedelta
Classe datetime.date
Você pode instanciar date
objetos da date
classe. Um objeto de data representa uma data (ano, mês e dia).
Exemplo 3: Objeto de data para representar uma data
import datetime d = datetime.date(2019, 4, 13) print(d)
Quando você executa o programa, a saída será:
13/04/2019
Se você está se perguntando, date()
no exemplo acima é um construtor da date
classe. O construtor leva três argumentos: ano, mês e dia.
A variável a é um date
objeto.
Só podemos importar date
classes do datetime
módulo. Veja como:
from datetime import date a = date(2019, 4, 13) print(a)
Exemplo 4: Obtenha a data atual
Você pode criar um date
objeto contendo a data atual usando um método de classe chamado today()
. Veja como:
from datetime import date today = date.today() print("Current date =", today)
Exemplo 5: obter data de um carimbo de data / hora
Também podemos criar date
objetos a partir de um carimbo de data / hora. Um carimbo de data / hora Unix é o número de segundos entre uma data específica e 1º de janeiro de 1970 no UTC. Você pode converter um carimbo de data / hora em data usando o fromtimestamp()
método.
from datetime import date timestamp = date.fromtimestamp(1326244364) print("Date =", timestamp)
Quando você executa o programa, a saída será:
Date = 11/01/2012
Exemplo 6: Imprima o ano, mês e dia de hoje
Podemos obter facilmente o ano, o mês, o dia, o dia da semana, etc. do objeto de data. Veja como:
from datetime import date # date object of today's date today = date.today() print("Current year:", today.year) print("Current month:", today.month) print("Current day:", today.day)
datetime.time
Um objeto de hora instanciado da time
classe representa a hora local.
Exemplo 7: Objeto de tempo para representar o tempo
from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("a =", a) # time(hour, minute and second) b = time(11, 34, 56) print("b =", b) # time(hour, minute and second) c = time(hour = 11, minute = 34, second = 56) print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566) print("d =", d)
Quando você executa o programa, a saída será:
a = 00:00:00 b = 11:34:56 c = 11:34:56 d = 11: 34: 56,234566
Exemplo 8: Imprimir hora, minuto, segundo e microssegundo
Depois de criar um time
objeto, você pode imprimir facilmente seus atributos, como hora, minuto etc.
from datetime import time a = time(11, 34, 56) print("hour =", a.hour) print("minute =", a.minute) print("second =", a.second) print("microsecond =", a.microsecond)
Quando você executa o exemplo, a saída será:
hora = 11 minutos = 34 segundos = 56 microssegundos = 0
Observe que não passamos o argumento de microssegundo. Portanto, seu valor padrão 0
é impresso.
datetime.datetime
The datetime
module has a class named dateclass
that can contain information from both date and time objects.
Example 9: Python datetime object
from datetime import datetime #datetime(year, month, day) a = datetime(2018, 11, 28) print(a) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2017, 11, 28, 23, 55, 59, 342380) print(b)
When you run the program, the output will be:
2018-11-28 00:00:00 2017-11-28 23:55:59.342380
The first three arguments year, month and day in the datetime()
constructor are mandatory.
Example 10: Print year, month, hour, minute and timestamp
from datetime import datetime a = datetime(2017, 11, 28, 23, 55, 59, 342380) print("year =", a.year) print("month =", a.month) print("hour =", a.hour) print("minute =", a.minute) print("timestamp =", a.timestamp())
When you run the program, the output will be:
year = 2017 month = 11 day = 28 hour = 23 minute = 55 timestamp = 1511913359.34238
datetime.timedelta
A timedelta
object represents the difference between two dates or times.
Example 11: Difference between two dates and times
from datetime import datetime, date t1 = date(year = 2018, month = 7, day = 12) t2 = date(year = 2017, month = 12, day = 23) t3 = t1 - t2 print("t3 =", t3) t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33) t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13) t6 = t4 - t5 print("t6 =", t6) print("type of t3 =", type(t3)) print("type of t6 =", type(t6))
When you run the program, the output will be:
t3 = 201 days, 0:00:00 t6 = -333 days, 1:14:20 type of t3 = type of t6 =
Notice, both t3 and t6 are of type.
Example 12: Difference between two timedelta objects
from datetime import timedelta t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33) t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54) t3 = t1 - t2 print("t3 =", t3)
When you run the program, the output will be:
t3 = 14 days, 13:55:39
Here, we have created two timedelta
objects t1 and t2, and their difference is printed on the screen.
Example 13: Printing negative timedelta object
from datetime import timedelta t1 = timedelta(seconds = 33) t2 = timedelta(seconds = 54) t3 = t1 - t2 print("t3 =", t3) print("t3 =", abs(t3))
When you run the program, the output will be:
t3 = -1 day, 23:59:39 t3 = 0:00:21
Example 14: Time duration in seconds
You can get the total number of seconds in a timedelta object using total_seconds()
method.
from datetime import timedelta t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423) print("total seconds =", t.total_seconds())
When you run the program, the output will be:
total seconds = 435633.233423
You can also find sum of two dates and times using +
operator. Also, you can multiply and divide a timedelta
object by integers and floats.
Python format datetime
The way date and time is represented may be different in different places, organizations etc. It's more common to use mm/dd/yyyy
in the US, whereas dd/mm/yyyy
is more common in the UK.
Python has strftime()
and strptime()
methods to handle this.
Python strftime() - datetime object to string
The strftime()
method is defined under classes date
, datetime
and time
. The method creates a formatted string from a given date
, datetime
or time
object.
Example 15: Format date using strftime()
from datetime import datetime # current date and time now = datetime.now() t = now.strftime("%H:%M:%S") print("time:", t) s1 = now.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format print("s1:", s1) s2 = now.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format print("s2:", s2)
When you run the program, the output will be something like:
time: 04:34:52 s1: 12/26/2018, 04:34:52 s2: 26/12/2018, 04:34:52
Here, %Y
, %m
, %d
, %H
etc. are format codes. The strftime()
method takes one or more format codes and returns a formatted string based on it.
In the above program, t, s1 and s2 are strings.
%Y
- year (0001,… , 2018, 2019,… , 9999)%m
- month (01, 02,… , 11, 12)%d
- day (01, 02,… , 30, 31)%H
- hour (00, 01,… , 22, 23%M
- minute (00, 01,… , 58, 59)%S
- second (00, 01,… , 58, 59)
To learn more about strftime()
and format codes, visit: Python strftime().
Python strptime() - string to datetime
The strptime()
method creates a datetime
object from a given string (representing date and time).
Example 16: strptime()
from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) date_object = datetime.strptime(date_string, "%d %B, %Y") print("date_object =", date_object)
When you run the program, the output will be:
date_string = 21 June, 2018 date_object = 2018-06-21 00:00:00
The strptime()
method takes two arguments:
- uma string representando a data e hora
- código de formato equivalente ao primeiro argumento
By the way, %d
, %B
e %Y
códigos de formato são usados para o dia, mês (nome completo) e no ano, respectivamente.
Visite Python strptime () para saber mais.
Gerenciando fuso horário em Python
Suponha que você esteja trabalhando em um projeto e precise exibir a data e a hora com base em seu fuso horário. Em vez de tentar controlar o fuso horário sozinho, sugerimos que use um módulo pytZ de terceiros.
from datetime import datetime import pytz local = datetime.now() print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S")) tz_NY = pytz.timezone('America/New_York') datetime_NY = datetime.now(tz_NY) print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S")) tz_London = pytz.timezone('Europe/London') datetime_London = datetime.now(tz_London) print("London:", datetime_London.strftime("%m/%d/%Y, %H:%M:%S"))
Quando você executa o programa, a saída será algo como:
Horário local: 20/12/2018 13: 10: 44.260462 Horário da América / New_York: 20/12/2018 13: 10: 44.260462 Horário da Europa / Londres: 20/12/2018 13: 10: 44,260462
Aqui, datetime_NY e datetime_London são objetos datetime que contêm a data e a hora atuais de seus respectivos fusos horários.