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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

strptime() en Python

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.

Exemple1:Chaine de caractères de l'objet date-heure

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'>

Comment fonctionne strptime() ?

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

Exemple2:Chaine de caractères de l'objet date-heure

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

Liste des codes de format

Le tableau suivant montre tous les codes de format que vous pouvez utiliser.

InstructionSignificationExemple
%aAbréviations des jours ouvrables.Sun, Mon, ...
%ANom complet du jour ouvrable.Sunday, Monday, ...
%wJour ouvrable exprimé en nombre décimal.0,1,...,6
%dUn jour du mois exprimé en nombre décimal avec zéro complément.01,02,...,31
%-dUn jour du mois exprimé en nombre décimal.1,2,...,30
%bAbréviations des mois.Jan, Feb, ..., Dec
%BNom complet du mois.January, February, ...
%mMois avec zéro complément, nombre décimal.01、02,...,12
%-mMois exprimé en nombre décimal.1,2,...,12
%yAnnée sans siècle, nombre décimal avec zéro complément.00、01,...,99
%-yAnnée sans siècle, nombre décimal.0,1,...,99
%YAnnée au siècle comme nombre décimal.2013、2019et
%HHour (24Heure de l'année), nombre décimal à zéro complément.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 of 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 number.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 before the first Sunday of a new year 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 before the first Monday of a new year 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 format of the language environment.13/9/30
%XThe appropriate time representation format of the language environment.07:06:05
%%The text character "%".%

ValueError in strptime()

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