How to Use the DateTime strptime() Function in Python

09/15/2021

Contents

In this article, you will learn how to use the dateTime strptime() function in Python.

DateTime strptime() Function

The strptime() function in Python is used to convert a string representing a date and time into a datetime object. The strptime() function parses a string representation of a date and time, according to a given format, and returns a datetime object.

Here’s an example:

import datetime

date_string = "23/02/2023"
date_object = datetime.datetime.strptime(date_string, "%d/%m/%Y")

print("Date:", date_object.date())

In the above example, the strptime() function is used to convert the date_string variable into a datetime object. The second argument to strptime() is the format string that specifies how the string is formatted. In this case, the format string “%d/%m/%Y” specifies that the string contains a day, month, and year separated by slashes.

The datetime object is then printed using the date() method to print only the date part.

Here are some common format codes that you can use with strptime():

  • %d: Day of the month as a zero-padded decimal number (01-31)
  • %m: Month as a zero-padded decimal number (01-12)
  • %Y: Year with century as a decimal number
  • %H: Hour (24-hour clock) as a zero-padded decimal number (00-23)
  • %M: Minute as a zero-padded decimal number (00-59)
  • %S: Second as a zero-padded decimal number (00-59)

You can also use other characters to separate the date and time parts in the format string, such as dashes or dots.

For example, if you have a string in the format “2023-02-23 15:30:45”, you can use the following format string:

date_string = "2023-02-23 15:30:45"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

In this example, the format string “%Y-%m-%d %H:%M:%S” specifies that the string contains a year, month, day, hour, minute, and second separated by a dash and a space.