strftime is a method available in Python’s datetime module. It stands for “string format time”. It is used to convert a datetime object into a string, formatted according to a specified format. The method takes one argument:
- The format string specifying the desired format of the output string
The format string is a combination of various format codes that represent different parts of the date and time, such as %Y for a 4-digit year, %m for a 2-digit month, %d for a 2-digit day, %H for a 2-digit hour, %M for a 2-digit minute, and %S for a 2-digit second.
Here’s an example:
from datetime import datetime
# Create a datetime object for the current date and time
now = datetime.now()
# Specify the desired format for the output string
date_format = “%Y-%m-%d %H:%M:%S”
# Convert the datetime object into a formatted string
formatted_date_string = now.strftime(date_format)
print(formatted_date_string)
This code will output the current date and time in the format “YYYY-MM-DD HH:MM:SS”, for example:
2023-04-26 12:34:56
In this example, the datetime object representing the current date and time is converted into a string using the format string “%Y-%m-%d %H:%M:%S”, which defines the desired format of the output string.