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

Tutoriales Básicos de Python

Control de Flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de Ficheros de Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de Python

strptime() en Python

En este artículo, aprenderá cómo crear un objeto datetime a partir de una cadena (con la ayuda de ejemplos).

El método strptime() crea un objeto datetime a partir de una cadena dadadatetimeobjeto.

Atención:Usted no puede crear un objeto datetime a partir de cada cadena. La cadena debe tener algún formato.

Ejemplo1:Fecha y hora del objeto de cadena

from datetime import datetime
date_string = "21 June, 2018"
print("date_string =", date_string)
print("date_string数据类型 =", type(date_string))
date_object  =  datetime.strptime(date_string,  "%d %B, %Y")
print("date_object =", date_object)
print("date_object tipo de datos  =",  type(date_object))

La salida del programa es:

date_string  = 21 June, 2018
date_string  tipo de datos  =  <class 'str'>
date_object  = 2018-06-21 00:00:00
date_object  tipo de datos  =  <class 'datetime.datetime'>

¿Cómo funciona strptime()?

strptime() tiene dos parámetros:

  • Cadena (se convertirá a fecha y hora)

  • Código de formato

Según la cadena utilizada y los códigos de formato, este método devuelve su equivalente objeto datetime.

En el ejemplo anterior:

Aquí,

  • %d-Representa un día del mes.Ejemplo: 01, 02,...,31

  • %B-Nombre completo del mes.Por ejemplo:January, February, etc

  • %Y-El año se representa con cuatro dígitos.Por ejemplo: 2018,2019etc

Ejemplo2:Fecha y hora del objeto de cadena

from datetime import datetime
dt_string = "12/11/2019 09:15:32"
# Fecha como dd / mm / formato yyyy
dt_object1 =  datetime.strptime(dt_string,  "%d/%m/%Y %H:%M:%S")
print("dt_object1 =",  dt_object1)
# Fecha como mm / dd / formato yyyy
dt_object2 =  datetime.strptime(dt_string,  "%m/%d/%Y %H:%M:%S")
print("dt_object2 =",  dt_object2)

La salida del programa es:

dt_object1 = 2019-11-12 09:15:32
dt_object2 = 2019-12-11 09:15:32

Lista de códigos de formato

La siguiente tabla muestra todos los códigos de formato que puede usar.

InstrucciónSignificadoEjemplo
%aAbreviatura del nombre del día laboral.Sun, Mon, ...
%ANombre completo del día laboral.Sunday, Monday, ...
%wDía laboral como número decimal.0,1,...,6
%dDía del mes con relleno cero como número decimal.01, 02,...,31
%-dDía del mes representado como número decimal.1,2,...,30
%bAbreviatura del mes.Jan, Feb, ..., Dec
%BNombre completo del mes.January, February, ...
%mMes con relleno cero como número decimal.01、02,...,12
%-mMes representado como número decimal.1,2,...,12
%yAño sin siglo, número decimal con relleno cero.00、01,...,99
%-yAño sin siglo como número decimal.0,1,...,99
%YAño como número decimal del siglo.2013,2019etc
%HHour (24Sistema horario), número decimal de relleno cero.00、01,...,23
%-HHour (24The decimal number of the 12-hour clock)0,1,...,23
%IHour (12The 12-hour clock), a zero-padded decimal number.01、02,...,12
%-IHour (12The decimal number of the 12-hour clock)1 2 2
%pThe morning or afternoon in the language environment.AM,PM
%MMinute, a zero-padded decimal number.00、01,...,59
%-MRepresented by a decimal number.0,1,...,59
%SThe second zero-padded decimal number.00、01,...,59
%-SThe second decimal digit.0,1,...,59
%fMicroseconds, a decimal number, padded with zeros on the left.000000-999999
%zThe UTC offset, formatted as+ HHMM or-HHMM。 
%ZThe time zone name. 
%jThe day of the year, represented by a zero-padded decimal number.001,002,...,366
%-jThe day of the year, represented by a decimal number.1,2,...,366
%UThe week number in a year (Sunday is the first day of the week). All days in the new year before the first Sunday are considered to be in the 0th week.00、01,...,53
%WThe week number in a year (Monday is the first day of the week). All days in the new year before the first Monday are considered to be in the 0th week.00、01,...,53
%cThe appropriate date and time representation of the language environment.Mon Sep 30 07:06:05 2013
%xThe appropriate date representation form of the language environment.13/9/30
%XThe appropriate time representation form of the language environment.07:06:05
%%The text character "%".%

ValueError in strptime()

If the string passed to strptime() (the first parameter) and the format code (the second parameter) do not match, a ValueError will be obtained. For example:

from datetime import datetime
date_string = "12/11/2018"
date_object = datetime.strptime(date_string, "%d %m %Y")
print("date_object =", date_object)

If you run this program, an error will occur.

ValueError: time data '12/11/2018' does not match format '%d %m %Y'

Recommended reading: strftime() en Python