Transform datetime to String without Microsecond Component in Python (3 Examples)

This post explains how to transform a datetime object to a string without a microsecond component in the Python programming language.

Creating Example Data & Loading datetime Module

We can load the datetime module as shown below:

from datetime import datetime

To create an example datetime object, we simply use the now() function:

datetime_x = datetime.now()
print(datetime_x)
# 2022-03-24 13:32:00.892475

Example 1: replace() Function to Exclude Microseconds from datetime Object

The first example applies the replace() function to generate a string object without microseconds:

string_x_2 = datetime_x.replace(microsecond = 0)
print(string_x_2)
# 2022-03-24 13:32:00

Example 2: str() & slice() Functions to Exclude Microseconds from datetime Object

The str() function transforms the datetime object into a string with microseconds.

Applying the slice() function to this string returns only the first 19 characters:

string_x_3 = str(datetime_x)[:19]
print(string_x_3)
# 2022-03-24 13:32:00

As you can see, this deletes the last part of the string, i.e. the microseconds component.

Example 3: isoformat() Function to Exclude Microseconds from datetime Object

The last method takes the datetime object and returns a character string representing the date in ISO 8601 format.

You have to specify the keyword ‘seconds’ within the isoformat function to get rid of the microseconds component:

string_x_1 = datetime_x.isoformat(' ', 'seconds')
print(string_x_1)
# 2022-03-24 13:32:00

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top