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

Tutorial Básica de Python

Control de flujo Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de Python

Fecha y hora (datetime) en Python

En este artículo, aprenderá a operar con fechas y horas en Python a través de ejemplos.

Python tiene un nombre llamadodatetimeEl módulo, utilizado para manejar fechas y horas. Antes de profundizar, creemos algunos programas simples relacionados con fechas y horas.

示例1Obtener la fecha y hora actual

import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)

When you run the program, the output will be similar to:

2020-04-13 17:09:49.015911

Aquí, utilizamos la declaración import datetime para importardatetimemódulo.

Una clase definida en el módulo datetime es la clase datetime. Luego, usamos el método now() para crear un objeto datetime que contenga la fecha y hora locales actuales.

示例2:Obtener fecha actual

import datetime
date_object = datetime.date.today()
print(date_object)

When you run the program, the output will be similar to:

2020-04-13

En este programa, usamos el método today() definido en la clase date para obtener un objeto date que contenga la fecha local actual.

¿Qué hay en datetime?

Podemos usardir()una función para obtener una lista de todas las propiedades del módulo.

import datetime
print(dir(datetime))

When running the program, the output is:

['MAXYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

Las clases comunes en el módulo datetime son:

  • clase date

  • clase time

  • clase datetime

  • clase timedelta

clase datetime.date

Puede instanciar un objeto date desde la clase date. El objeto date representa una fecha (año, mes y día).

示例3:Representa el objeto Date de la fecha

import datetime
d = datetime.date(2019, 4, 13)
print(d)

When running the program, the output is:

2019-04-13

Si lo desea, el date() del ejemplo anterior es el constructor de la clase date. El constructor tiene tres parámetros: año, mes y día.

variableaes un objeto date.

Sólo podemos importar la clase date del módulo datetime. Es así:

from datetime import date
a = date(2019, 4, 13)
print(a)

示例4:Obtener fecha actual

Puede usar un método de clase llamado today() para crear un objeto date que contenga la fecha actual. El método es el siguiente:

from datetime import date
today = date.today()
print("Fecha actual =", today)

示例5:Obtener fecha desde timestamp

También podemos crear un objeto fecha a partir de un timestamp. El timestamp Unix es la cantidad de segundos desde una fecha específica hasta UTC1970 año1mes1los segundos entre dos días. Se puede usar el método fromtimestamp() para convertir un timestamp a una fecha.

from datetime import date
timestamp = date.fromtimestamp(1576244364)
print("日期 =", timestamp)

When running the program, the output is:

日期 = 2019-12-13

示例6:打印今天的年,月和日

我们可以轻松地从日期对象获取年,月,日,星期几等。就是这样:

from datetime import date
# 今天的日期对象
today = date.today() 
print("当前年:", today.year)
print("当前月:", today.month)
print("当前日:", today.day)

datetime.time

从time类示例化的时间对象表示本地时间。

示例7:表示时间的时间对象

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)

When running the program, the output is:

a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566

示例8:打印时,分,秒和微秒

创建time对象后,您可以轻松打印其属性,例如小时分钟等。

from datetime import time
a = time(11, 34, 56)
print("小时=", a.hour)
print("分钟=", a.minute)
print("秒=", a.second)
print("微秒=", a.microsecond)

运行示例时,输出将是:

小时= 11
分钟= 34
秒= 56
微秒= 0

注意,我们还没有传递微秒参数。因此,将打印其默认值0。

datetime.datetime

datetime模块有一个名为date的class类,可以包含来自dateandtime对象的信息。

示例9:Python datetime对象

from datetime import datetime
#datetime(year, month, day)
a = datetime(2019, 11, 28)
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2019, 11, 28, 23, 55, 59, 342380)
print(b)

When running the program, the output is:

2019-11-28 00:00:00
2019-11-28 23:55:59.342380

Los tres primeros parámetros year、month y day del constructor datetime() son obligatorios.

示例10:Imprimir año, mes, hora, minuto y timestamp

from datetime import datetime
a = datetime(2019, 12, 28, 23, 55, 59, 342380)
print("Año =", a.year)
print("Mes =", a.month)
print("Día =", a.day)
print("Hora =", a.hour)
print("Mes =", a.minute)
print("Timestamp =", a.timestamp())

When running the program, the output is:

Año = 2019
Mes = 12
Día = 28
Hora = 23
Mes = 55
Timestamp = 1577548559.34238

datetime.timedelta

El objeto timedelta representa la diferencia de tiempo entre dos fechas o horas.

示例11:Diferencia de tiempo entre dos fechas y horas

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 running the program, the output is:

t3 = 201 days, 0:00:00
t6 = -333 days, 1:14:20
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>

Notar que,t3andt6son del tipo <class 'datetime.timedelta'>.

示例12:Diferencia de tiempo entre dos objetos timedelta

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 running the program, the output is:

t3 = 14 days, 13:55:39

Aquí, creamos dos objetos timedeltat1andt2,los días de diferencia directos se imprimen en la pantalla.

示例13:Imprimir el objeto timedelta negativo

from datetime import timedelta
t1 = timedelta(seconds = 33)
t2 = timedelta(seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
print("t3 =", abs(t3))

When running the program, the output is:

t3 = -1 day, 23:59:39
t3 = 0:00:21

示例14:Duración (en segundos)

Puede obtener el número total de segundos del objeto timedelta utilizando el método total_seconds().

from datetime import timedelta
t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)
print("total seconds =", t.total_seconds())

When running the program, the output is:

total seconds = 435633.233423

您还可以使用+运算符找到两个日期和时间的总和。同样,您可以将timedelta对象乘以整数和浮点数。

Python格式日期时间

日期和时间的表示方式在不同的地方,组织等中可能有所不同。在美国,使用mm / dd / yyyy更为常见,而在英国使用dd / mm / yyyy更为常见。

Python有strftime()和strptime()方法来处理这个问题。

strftime() en Python-字符串的日期时间对象

strftime()方法是在date、datetime和time类下面定义的。该方法根据给定的日期、日期时间或时间对象创建格式化的字符串。

示例15:使用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 similar to:

time: 04:34:52
s1: 12/26/2018, 04:34:52
s2: 26/12/2018, 04:34:52

这里%Y,%m,%d,%H等都是格式代码。strftime()方法采用一个或多个格式代码,并根据该代码返回格式化的字符串。

在上面的程序中,ts1ands2是字符串。

  • %Y -年[0001,...,2018,2019,...,9999]

  • %m -月[01,02,...,11,12]

  • %d -天[01,02,...,30,31]

  • %H -小时[00,01,...,22,23

  • %M -分钟[00,01,...,58,59]

  • %S -秒[00,01,...,58,59]

要了解有关strftime()代码并设置其格式的更多信息,请访问:strftime() en Python

strptime() en Python-日期时间的字符串

strptime()方法从一个给定的字符串(表示日期和时间)创建一个datetime对象。

示例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 running the program, the output is:

date_string = 21 June, 2018
date_object = 2018-06-21 00:00:00

The strptime() method has two parameters:

  1. String representing date and time

  2. Equivalent to the format code of the first parameter

By the way, the %d, %B and %Y format codes are used for day, month (full name) and year, respectively.

Visitstrptime() en PythonFor more information.

Handling time zones in Python

Assuming you are working on a project that needs to display the date and time according to its time zone. We recommend using third-partypytz moduleInstead of handling the time zone yourself.

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")

When you run the program, the output will be similar to:

Local time: 2018-12-20 13:10:44.260462
America/New_York time: 2018-12-20 13:10:44.260462
Europe/London time: 2018-12-20 13:10:44.260462

Here,datetime_NYanddatetime_LondonIs a datetime object containing the current date and time with their respective time zones.