Skip to content

What is the difference between strftime() and strptime()?

  • by

strftime() and strptime() are both functions used for formatting and parsing dates and times in Python, but they serve different purposes.

strftime() is used to format a datetime object into a string representation, while strptime() is used to parse a string into a datetime object.

The syntax for strftime() and strptime() is different. Here’s a breakdown of the syntax for each function:

strftime() Syntax (String Format Time): The strftime() function takes a datetime object and a format string as input and returns a formatted string representation of the date and time.

strftime(format)

strptime() Syntax (String Parse Time): The strptime() function takes a string and a format string as input and returns a datetime object representing the parsed date and time.

strptime(date_string, format)

Here’s a tabular format highlighting the differences between strftime() and strptime():

FunctionPurposeInputOutput
strftime()Formats a datetime object into a string representationdatetime object, format stringFormatted string
strptime()Parses a string representing a date and time into a datetime objectString, format stringdatetime object

Difference between strftime() and strptime() example

Here are examples showcasing the difference between strftime() and strptime():

1. Example of strftime() (String Format Time):

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)

2. Example of strptime() (String Parse Time):

from datetime import datetime

date_string = "2023-06-29 14:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date)

Output:

What is the difference between strftime() and strptime()?

Comment if you have any doubts or suggestions on this Python difference topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading