datetime.strptime()

DateTime

Parses a date string into a datetime object using a format string.

Signature

datetime.strptime(date_string, format)

Returns

datetime

Example

from datetime import datetime
dt = datetime.strptime('2024-03-15', '%Y-%m-%d')
print(dt.year)   # 2024
print(dt.month)  # 3

About datetime.strptime()

datetime.strptime is a Python datetime function with the signature datetime.strptime(date_string, format). Parses a date string into a datetime object using a format string. It returns a value of type datetime.

Python provides a rich set of built-in functions and standard library modules that cover common programming tasks. Understanding these functions helps you write more idiomatic, efficient Python code. The datetime.strptimefunction is commonly used in data processing, web development, scripting, and automation tasks.

When working with datetime.strptime(), consider edge cases like empty inputs, None values, and type mismatches. Python's duck typing means many built-in functions work with any object that implements the required protocol (e.g., __len__ for len(), __iter__ for iteration). This flexibility is a key strength of Python's design philosophy.

Related Functions