Logo

Developer learning path

Python

Date and Time Formatting in Python

Date and Time Formatting

15

#description

Date and time formatting refers to the process of converting date and time objects into a specified string format. In Python, this is typically done using the strftime() method, which stands for "string format time".

The strftime() method takes a date or time object and a format string as input, and returns a string that represents the date and time in the specified format. The format string contains various directives that are used to specify how different parts of the date and time should be represented in the output string.

For example, the directive %Y represents the year with century, %m represents the month as a zero-padded decimal number, %d represents the day of the month as a zero-padded decimal number, %H represents the hour as a zero-padded decimal number using a 24-hour clock, %M represents the minute as a zero-padded decimal number, and %S represents the second as a zero-padded decimal number.

Here's an example of how to use strftime() to format a datetime object:

                    
import datetime

now = datetime.datetime.now()

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

print(formatted_date)
                  

This code will output something like 2022-05-10 14:30:15, representing the current date and time in the specified format.

Overall, date and time formatting is an important aspect of working with datetime objects in Python, as it enables you to convert these objects into a format that is more easily readable and usable in various contexts, such as for displaying dates and times in a user interface or writing them to a file.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.