w3resource

Python: Drop microseconds from datetime

Python Datetime: Exercise-17 with Solution

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:

Flowchart: Drop microseconds from datetime.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/date-time-exercise/python-date-time-exercise-17.php