How to get min, seconds and milliseconds from datetime.now() in Python?



Python's datetime module is used to extract various components of the current date and time, such as minutes, seconds, and even milliseconds.

The datetime.now() method defined in the datetime module returns the current local date and time as a datetime object. This object allows us to access its individual components like minute, second, and millisecond.

Using Attributes of datetime.now() to Extract Values

Here we use the datetime.now() method to get the current minutes, seconds, and milliseconds. The now() function is defined under the datetime module. And retrieve the current minutes, seconds, and milliseconds by using .minute, .second, and .microsecond, respectively.

Example

In the following example code, we get the current minutes, seconds, and milliseconds using the datetime.now() method.

from datetime import datetime
now = datetime.now()
print("Today's date is:", now)
print("Minutes",now.minute)
print("Seconds",now.second)
print("Milliseconds",now.microsecond)

Following is the output of the above code:

Today's date is: 2022-09-05 10:12:31.476711
Minutes 12
Seconds 31
Milliseconds 476711

Using datetime.now() and strftime() Format Time

Here we use the strftime() method, which is provided by the datetime module. We have used the datetime.now() method to get the current date. Then we format this date by using the strftime() method. In this case, we format a string in the form of "minutes: seconds. milliseconds".

Example

The following is an example code to get the current minutes, seconds and milliseconds using the datetime.now() and strftime() methods.

from datetime import datetime
curr_time = datetime.now()
formatted_time = curr_time.strftime('%M:%S.%f')
print("Formatted time in Minutes:Seconds:Milliseconds is",formatted_time)

Following is the output of the above code:

Formatted time in Minutes:Seconds:Milliseconds is 11:40.325948

Creating a Custom Time String with Minutes, Seconds, and Milliseconds

Sometimes, we may want to create a custom time string using the input values obtained from datetime.now() method. We can combine .minute, .second, and the converted .microsecond for this.

Example

The following code gets the current time, extracts minutes, seconds, and converts microseconds to milliseconds, then formats and prints it as a string in the "Minutes: Seconds: Milliseconds" format.

from datetime import datetime

now = datetime.now()
time_str = f"{now.minute}:{now.second}.{now.microsecond // 1000}"
print("Time (M:S.ms):", time_str)

Following is the output of the above code:

Time (M:S.ms): 12:31.476
Updated on: 2025-08-28T12:17:24+05:30

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements