Skip to content

strftime python

In Python, the strftime method is used to format date and time objects as strings according to a specified format. It stands for “string format time.” This method is part of the datetime module, so you need to import the datetime module to use it. Here’s how you can use strftime:

pythonCopy codeimport datetime

# Create a datetime object
now = datetime.datetime.now()

# Format the datetime object as a string using strftime
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")

print(formatted_date)

In the example above:

  • We import the datetime module.
  • We create a datetime object named now representing the current date and time.
  • We use the strftime method to format the now object as a string. The argument to strftime is a format string that specifies how you want the date and time to be displayed. The format codes used in the format string dictate what parts of the date and time are included and how they are formatted.

Here are some commonly used format codes:

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

You can combine these format codes with other characters to create the desired output format for your date and time string.

For more information about the available format codes and their meanings, you can refer to the Python documentation: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)