Convert DateTime to String With Milliseconds in Python

Convert DateTime to String With Milliseconds in Python

Manav Narula Feb-07, 2021 Jan-25, 2021 Python Python DateTime
  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
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python DateTime

  • Convert Pandas Column to Datetime
  • Get the Current Time in Python
  • Get the Day of the Week in Python
  • Convert String to Datetime in Python
  • Find the Last Day of the Month Using Python
  • Determine Leap Year in Python