English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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'>
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
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
La siguiente tabla muestra todos los códigos de formato que puede usar.
Instrucción | Significado | Ejemplo |
%a | Abreviatura del nombre del día laboral. | Sun, Mon, ... |
%A | Nombre completo del día laboral. | Sunday, Monday, ... |
%w | Día laboral como número decimal. | 0,1,...,6 |
%d | Día del mes con relleno cero como número decimal. | 01, 02,...,31 |
%-d | Día del mes representado como número decimal. | 1,2,...,30 |
%b | Abreviatura del mes. | Jan, Feb, ..., Dec |
%B | Nombre completo del mes. | January, February, ... |
%m | Mes con relleno cero como número decimal. | 01、02,...,12 |
%-m | Mes representado como número decimal. | 1,2,...,12 |
%y | Año sin siglo, número decimal con relleno cero. | 00、01,...,99 |
%-y | Año sin siglo como número decimal. | 0,1,...,99 |
%Y | Año como número decimal del siglo. | 2013,2019etc |
%H | Hour (24Sistema horario), número decimal de relleno cero. | 00、01,...,23 |
%-H | Hour (24The decimal number of the 12-hour clock) | 0,1,...,23 |
%I | Hour (12The 12-hour clock), a zero-padded decimal number. | 01、02,...,12 |
%-I | Hour (12The decimal number of the 12-hour clock) | 1 2 2 |
%p | The morning or afternoon in the language environment. | AM,PM |
%M | Minute, a zero-padded decimal number. | 00、01,...,59 |
%-M | Represented by a decimal number. | 0,1,...,59 |
%S | The second zero-padded decimal number. | 00、01,...,59 |
%-S | The second decimal digit. | 0,1,...,59 |
%f | Microseconds, a decimal number, padded with zeros on the left. | 000000-999999 |
%z | The UTC offset, formatted as+ HHMM or-HHMM。 | |
%Z | The time zone name. | |
%j | The day of the year, represented by a zero-padded decimal number. | 001,002,...,366 |
%-j | The day of the year, represented by a decimal number. | 1,2,...,366 |
%U | The 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 |
%W | The 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 |
%c | The appropriate date and time representation of the language environment. | Mon Sep 30 07:06:05 2013 |
%x | The appropriate date representation form of the language environment. | 13/9/30 |
%X | The appropriate time representation form of the language environment. | 07:06:05 |
%% | The text character "%". | % |
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