Python datetime.strftime()
In Python, the strftime()
method is used to convert a datetime
object to a string representation. It takes a format string as an argument, which contains various format codes that are replaced with the corresponding values from the datetime
object.
Here's an example of how to use the strftime()
method in Python:
import datetime # Create a datetime object dt = datetime.datetime(2022, 3, 1, 15, 45, 23) # Convert datetime object to string str_dt = dt.strftime("%Y-%m-%d %H:%M:%S") # Print the string representation print(str_dt)
Output:
2022-03-01 15:45:23
In this example, we created a datetime
object representing March 1st, 2022 at 3:45:23 PM. We then used the strftime()
method to convert this datetime
object to a string representation using the format string "%Y-%m-%d %H:%M:%S"
. This format string contains various format codes such as %Y
(year), %m
(month), %d
(day), %H
(hour), %M
(minute), and %S
(second), which are replaced with the corresponding values from the datetime
object. Finally, we printed the resulting string representation using the print()
function.
Here are some common format codes used with the strftime()
method:
%Y
: Year with century as a decimal number.%m
: Month as a zero-padded decimal number.%d
: Day of the month as a zero-padded decimal number.%H
: Hour (24-hour clock) as a zero-padded decimal number.%M
: Minute as a zero-padded decimal number.%S
: Second as a zero-padded decimal number.%A
: Full weekday name.%a
: Abbreviated weekday name.%B
: Full month name.%b
: Abbreviated month name.%c
: Date and time representation.%x
: Date representation.%X
: Time representation.