.strptime()
Published Jan 12, 2025
Contribute to Docs
The .strptime()
is a method included in the datetime
module. It is used to parse a string representing a date and/or time and convert it into a datetime
object using a specified format.
Syntax
from datetime import datetime
datetime.strptime(date_string, format)
date_string
: The string representing the date and/or time to be parsed.format
: A string that defines the structure ofdate_string
using format codes from thedatetime
module (e.g.,%Y
for a four-digit year,%m
for a two-digit month).
It returns a datetime
object, which represents the parsed date and time from the provided date_string
according to the specified format
.
Example
In the following example, the .strptime()
method is used to parse a date-time string into a datetime
object based on the specified format:
from datetime import datetime# Define the date-time string and formatdatetime_string = "27/12/2024 15:30:00"datetime_format = "%d/%m/%Y %H:%M:%S"# Parse the string into a datetime objectdt_object = datetime.strptime(datetime_string, datetime_format)print(dt_object)
The code above produces an output as:
2024-12-27 15:30:00
Codebyte Example
Run the following codebyte example to understand the use of the .strptime()
method:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours