195k views
2 votes
How to remove microseconds from datetime in python

1 Answer

2 votes

Final answer:

To remove microseconds from a datetime object in Python, use the replace() method of the datetime object to set microsecond=0. This will result in a new datetime object with microseconds removed.

Step-by-step explanation:

To remove microseconds from a datetime object in Python, you can replace the microsecond part with zero using the replace() method of the datetime object. Here's a step-by-step example:

from datetime import datetime

# Assuming you have a datetime object with microseconds
dt_with_microseconds = datetime.now()

# To remove microseconds, replace them with zero
dt_without_microseconds = dt_with_microseconds.replace(microsecond=0)

print('Before:', dt_with_microseconds)
print('After: ', dt_without_microseconds)

In this example, dt_with_microseconds contains the current datetime including microseconds. We create a new datetime object dt_without_microseconds by using the replace() method to set microsecond=0. The resulting datetime will have the microseconds set to zero, effectively removing them.

User Patrick Perry
by
7.8k points