Python: Drop microseconds from datetime
17. Drop Microseconds
Write a Python program to drop microseconds from datetime.
Sample Solution:
Python Code:
# Import the datetime module
import datetime
# Get the current date and time, then remove the microseconds from the time component
dt = datetime.datetime.today().replace(microsecond=0)
# Print an empty line
print()
# Print the current date and time (with microseconds removed)
print(dt)
# Print an empty line
print()
Output:
2017-05-06 14:17:47
Explanation:
In the exercise above,
- The code imports the "datetime" module.
- Get the current date and time:
- It retrieves the current date and time using "datetime.datetime.today()".
- Then, it removes the microseconds from the time component using the "replace()" method with the argument 'microsecond=0'.
- Finally it prints the current date and time with microseconds removed using "print(dt)".
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to remove the microseconds from a datetime object and then display the result in "YYYY-MM-DD HH:MM:SS" format.
- Write a Python function that takes a datetime with microseconds, drops the microseconds, and then returns a formatted string.
- Write a Python script to truncate the microseconds from the current time and then compare it with the original time to show the difference.
- Write a Python program to convert a datetime object to a string without microseconds and then parse it back to a datetime object.
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program to add year(s) with a given date and display the new date.
Next: Write a Python program to get days between two dates.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.