English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet article, vous apprendrez à créer des objets datetime à partir de chaînes de caractères (sous l'aide d'exemples).
La méthode strptime() crée un objet datetime à partir de la chaîne donnéedatetimeObjet.
Remarque :Vous ne pouvez pas créer d'objet datetime à partir de chaque chaîne. La chaîne doit suivre un certain format.
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数据类型 =", type(date_object))
La sortie de ce programme est :
date_string = 21 June, 2018 date_string type de données = <class 'str'> date_object = 2018-06-21 00:00:00 date_object type de données = <class 'datetime.datetime'>
La méthode strptime() a deux paramètres :
Chaîne de caractères (qui sera convertie en date-heure)
Codes de format
Selon la chaîne de caractères utilisée et les codes de format, cette méthode retourne son équivalent objet datetime.
Dans l'exemple ci-dessus :
Ici,
%d-Réprésente un jour du mois.Exemple : 01,02,...,31
%B-Noms complets des mois.Par exemple :January, February, etc.
%Y-L'année est exprimée en quatre chiffres.Par exemple : 2018、2019et
from datetime import datetime dt_string = "12/11/2019 09:15:32" # Date est dd / mm / format yyyy dt_object1 = datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S") print("dt_object1 =", dt_object1) # Date est mm / dd / format yyyy dt_object2 = datetime.strptime(dt_string, "%m/%d/%Y %H:%M:%S") print("dt_object2 =", dt_object2)
La sortie de ce programme est :
dt_object1 = 2019-11-12 09:15:32 dt_object2 = 2019-12-11 09:15:32
Le tableau suivant montre tous les codes de format que vous pouvez utiliser.
Instruction | Signification | Exemple |
%a | Abréviations des jours ouvrables. | Sun, Mon, ... |
%A | Nom complet du jour ouvrable. | Sunday, Monday, ... |
%w | Jour ouvrable exprimé en nombre décimal. | 0,1,...,6 |
%d | Un jour du mois exprimé en nombre décimal avec zéro complément. | 01,02,...,31 |
%-d | Un jour du mois exprimé en nombre décimal. | 1,2,...,30 |
%b | Abréviations des mois. | Jan, Feb, ..., Dec |
%B | Nom complet du mois. | January, February, ... |
%m | Mois avec zéro complément, nombre décimal. | 01、02,...,12 |
%-m | Mois exprimé en nombre décimal. | 1,2,...,12 |
%y | Année sans siècle, nombre décimal avec zéro complément. | 00、01,...,99 |
%-y | Année sans siècle, nombre décimal. | 0,1,...,99 |
%Y | Année au siècle comme nombre décimal. | 2013、2019et |
%H | Hour (24Heure de l'année), nombre décimal à zéro complément. | 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 of 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 number. | 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 before the first Sunday of a new year 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 before the first Monday of a new year 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 format of the language environment. | 13/9/30 |
%X | The appropriate time representation format of the language environment. | 07:06:05 |
%% | The text character "%". | % |
If the string passed to the 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