How To Convert Python Datetime Objects To String

Avatar

By squashlabs, Last Updated: November 2, 2023

How To Convert Python Datetime Objects To String

There are several ways to convert a Python datetime object to a string representation of a date. In this answer, we will explore two common methods: using the strftime() method and the str() function.

Using the strftime() Method

The strftime() method is a useful tool in Python’s datetime module that allows you to format datetime objects into string representations based on a specified format string. Here’s how you can use it to convert a datetime object to a string of date:

import datetime

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

# Format the datetime object to a string of date
formatted_date = now.strftime("%Y-%m-%d")

# Print the formatted date
print(formatted_date)

Output:

2022-06-28

In the code snippet above, we import the datetime module and create a datetime object called now, which represents the current date and time. We then use the strftime() method on the now object, passing in the format string "%Y-%m-%d", which specifies the desired format for the date. The %Y represents the four-digit year, %m represents the month with leading zeros, and %d represents the day of the month with leading zeros. The strftime() method returns a formatted string of the date, which we assign to the variable formatted_date and print it out.

It’s important to note that the strftime() method supports a wide range of format codes, allowing you to customize the output according to your needs. Here are some common format codes for date formatting:

%Y: Four-digit year
%y: Two-digit year
%m: Month with leading zeros
%b: Abbreviated month name
%B: Full month name
%d: Day of the month with leading zeros
%A: Full weekday name
%a: Abbreviated weekday name

For a complete list of format codes, you can refer to the official Python documentation: strftime() and strptime() Behavior

Related Article: How To Limit Floats To Two Decimal Points In Python

Using the str() Function

Another simple way to convert a Python datetime object to a string of date is by using the str() function. The str() function converts the datetime object to its default string representation, which includes the date and time information. To extract only the date portion, we can manipulate the string using string slicing or the split() method. Here’s an example:

import datetime

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

# Convert the datetime object to a string
date_string = str(now)

# Extract only the date portion
formatted_date = date_string[:10]

# Print the formatted date
print(formatted_date)

Output:

2022-06-28

In the code snippet above, we create a datetime object called now representing the current date and time. We then convert the datetime object to a string using the str() function and assign it to the variable date_string. Since the default string representation of a datetime object includes both the date and time information, we use string slicing to extract only the first 10 characters, which represent the date portion. The resulting string is assigned to the variable formatted_date and printed out.

Although using the str() function is a straightforward approach, it may not be as flexible as using the strftime() method when it comes to customizing the date format. If you require more control over the date format, it is recommended to use the strftime() method instead.

Related Article: How To Rename A File With Python

More Articles from the Python Tutorial: From Basics to Advanced Concepts series:

How To Check If List Is Empty In Python

Determining if a list is empty in Python can be achieved using simple code examples. Two common methods are using the len() function and the not operator. This article... read more

How To Check If a File Exists In Python

Checking if a file exists in Python is a common task for many developers. This article provides simple code snippets and explanations on how to check file existence... read more

How to Use Inline If Statements for Print in Python

A simple guide to using inline if statements for print in Python. Learn how to use multiple inline if statements, incorporate them with string formatting, and follow... read more

How to Use Stripchar on a String in Python

Learn how to use the stripchar function in Python to manipulate strings. This article covers various methods such as strip(), replace(), and regular expressions. Gain... read more

How To Delete A File Or Folder In Python

Deleting files or folders using Python is a common task in software development. In this article, we will guide you through the process step-by-step, using simple... read more

How To Move A File In Python

Learn how to move a file in Python with this simple guide. Python move file tutorial for beginners. This article discusses why the question of moving files in Python is... read more