Transform datetime into String with Milliseconds in Python (3 Examples)

This post explains how to transform a datetime object into string with milliseconds in Python.

Creating Example Data & Loading datetime Module

We can import the datetime module as shown below.

from datetime import datetime

Generating an example datetime object:

dt_x = datetime.today()
print(dt_x)
# 2022-03-15 17:11:04.239319

Example 1: Set datetime Object to String with Milliseconds Using isoformat() Function

In this example, the isoformat() function from the datetime module is used to delete milliseconds from the output.

The isoformat() function returns the datetime object input as a string showing the date in ISO 8601 format.

string_x1 = dt_x.isoformat(sep = ' ', timespec = 'milliseconds')
print(string_x1)
# 2022-03-15 17:11:04.239

Example 2: Set datetime Object to String with Milliseconds Using strftime() Function

In this case, the strftime() Function is used to transform datetime object to character string with milli and microseconds.

string_x2 = dt_x.strftime('%Y-%m-%d %H:%M:%S.%f')
print(string_x2)
# 2022-03-15 17:11:04.239319

Example 3: Set datetime Object to String with Milliseconds Using str() Function

Another opportunity is given by the str() function, as you can see in the output of the following Python code:

string_x3 = str(dt_x)
print(string_x3)
# 2022-03-15 17:11:04.239319

 

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. Required fields are marked *

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