Converting datetime into string in Python

Let’s see how to convert a datetime into a string in Python.

This conversion can be done using the strftime() method from the datetime class.

This example shows a few different formats for current date and time:

  • Default date and time
  • Date with a format I defined
  • Time with a format I defined
  • Date and time with a format I defined
from datetime import datetime

current_date = datetime.now()

print(current_date)

print(current_date.strftime('%m/%d/%Y'))

print(current_date.strftime("%H:%M:%S"))

print(current_date.strftime('%a %b %d %H:%M:%S %Y'))
2020-04-25 23:21:12.578367
04/25/2020
23:22:21
Sat Apr 25 23:22:21 2020

The format codes used are:

  • %a: Weekday as locale’s abbreviated name.
  • %b: Month as locale’s abbreviated name.
  • %m: Month as a zero-padded decimal number.
  • %d: Day of the month as a zero-padded decimal number.
  • %Y: Year with century as a 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.

You can check the official documentation for other Format Codes to convert to different formats.

Watch this Content