1. Home
  2. Coding
  3. Format DateTime in Python

Format DateTime in Python

Share

To format a DateTime in Python we can use the strftime() function from the datetime module.

In Python, we can handle Time, Date, and DateTime using the datetime module. To format a datetime in Python, which means to “transform” an object of type datetime into a string according to a specific format, we can take advantage of the strftime() method that is provided by the datetime class.

If you want to know how to use strftime, this is the right place for you! In this article we will see a practical example on how to format a DateTime object in Python.

Example of Formatting a DateTime object in Python

In the following snippet we simply use strftime function to convert the current_datetime variable into multiple formats:

from datetime import datetime

current_datetime = datetime(2021, 11, 27, 16, 20, 0, 0)

# datetime in d/m/Y H:M:S format
date_time = current_datetime.strftime("%d/%m/%Y, %H:%M:%S")
print("datetime: %s" % date_time)

# datetime in Y-m-d H:M:S format
date_time = current_datetime.strftime("%Y-%m-%d, %H:%M:%S")
print("datetime: %s" % date_time)

# format date
date = current_datetime.strftime("%d/%m/%Y")
print("date: %s" % time)

# format time
time = current_datetime.strftime("%H:%M:%S")
print("time: %s" % time)

# day
day = current_datetime.strftime("%d")
print("day: %s" % day)

# month
month = current_datetime.strftime("%m")
print("month: %s" % month)

# year
year = current_datetime.strftime("%Y")
print("year: %s" % year)

In just a few lines of code, we formatted a datetime objects into multiple strings, yei! As you saw from the example above, we have used different formats based on our needs. Let’s see now how it looks if we try to run the previous line of code:

datetime: 27/11/2021, 16:20:00
datetime: 2021-11-27, 16:20:00
date: 27/11/2021
time: 16:20:00
day: 27
month: 11
year: 2021

That was easy!

If this is not enough for you, you can combine different directives and pick the one that suits your specific needs. The good news is that the strftime method follows the 1989 C standards, this means that there are a lot more supported time formats. The following image contains just a few of them:

If you want to learn more about how to convert Strings and DateTimes you can read our complete article on “Python string to DateTime and DateTime to string“.

External links:

If you like our post, please share it: