Convert DateTime to String With Milliseconds in Python

  1. Use the strftime() Method to Format DateTime to String
  2. Use the isoformat() Method to Format DateTime to String
  3. Use the str() Function to Format DateTime to String

The datetime module in Python allows us to create date and time objects easily manipulated and converted to different formats.

This tutorial will cover how to convert a datetime object to a string containing the milliseconds.

Use the strftime() Method to Format DateTime to String

The strftime() method returns a string based on a specific format specified as a string in the argument.

from datetime import datetime

date_s = (datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))

print(date_s)

Output:

2021-01-23 02:54:59.963001
Note

If we only import datetime, we would have to use datetime.datetime.now() to get the current date-time.

The %Y-%m-%d %H:%M:%S.%f is the string format. The now() method returns a datetime.datetime object of the current date and time. Notice that the final output has microseconds that could be easily truncated to milliseconds. For example:

from datetime import datetime

date_s = (datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

print(date_s)

Output:

2021-01-23 03:00:29.052

Use the isoformat() Method to Format DateTime to String

The isoformat() method of the datetime class returns a string representing the date in ISO 8601 format. We can specify the character which separates the date and time to be ' ' using the sep parameter and the timespace parameter that determines the time component to be milliseconds.

from datetime import datetime

date_s = datetime.now().isoformat(sep=' ', timespec='milliseconds')

print(date_s)

Output:

2021-01-23 03:15:35.322

Use the str() Function to Format DateTime to String

We can directly pass the datetime object to the str() function to get the string in the standard date and time format. This method is faster than the above methods, but we could specify the string format.

We can also simply remove the last three digits from the string to get the final result in milliseconds.

from datetime import datetime

t = datetime.now()
date_s = str(t)[:-3]

print(date_s)

Output:

2021-01-23 05:56:26.266
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.