Open In App

Remove Seconds from the Datetime in Python

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, the datetime module provides classes for manipulating dates and times. Sometimes we may need to remove the seconds component from a datetime object, either for display purposes, to store in a database, or for formatting consistency. In this article we will explore different approaches to remove seconds from the Datetime.

Removing Seconds from the Datetime in Python:

Below are the possible approaches to remove seconds from the Datetime in Python:

  • Using replace method of datetime class.
  • Using string formatting.

Using replace method of datetime class

In this approach, we will use the replace method datetime class. This method creates a new datetime instance with the specified attributes replaced by new values. Here we will set the second and microsecond attributes to zero so we can remove the seconds and microseconds from the datetime object.

Syntax:

new_datetime = original_datetime.replace(second=0, microsecond=0)

Example: This example uses the replace method to remove the seconds from the Datetime in Python.

Python
from datetime import datetime

# Original datetime
dt = datetime.now()
print("Original datetime:", dt)

# set seconds and microseconds to zero
dt_truncated = dt.replace(second=0, microsecond=0)
print("Truncated datetime:", dt_truncated)

Output:

Original datetime: 2024-05-27 09:20:41.599663
Truncated datetime: 2024-05-27 09:20:00

Using string formatting

In this approach we will use string formatting, it allows us to convert a datetime object to a string in a specific format. By using the strftime method with a format string that excludes seconds ('%Y-%m-%d %H:%M') we can create a formatted string without seconds.

Syntax:

formatted_datetime = original_datetime.strftime('%Y-%m-%d %H:%M')

Example: This example uses string formatting concept to remove the seconds from the Datetime in Python.

Python
from datetime import datetime

original_datetime = datetime.now()
formatted_datetime = original_datetime.strftime('%Y-%m-%d %H:%M')

print("Original:", original_datetime)
print("Formatted:", formatted_datetime)

Output:

Original: 2024-05-27 09:26:51.236716
Formatted: 2024-05-27 09:26

Article Tags :
Practice Tags :

Similar Reads