This article focuses on how to remove seconds on Python datetime objects. The seconds can be removed in two ways – simply truncating seconds by turning them to 0 or by rounding off seconds into minutes.
In this post, we assume you want to work with datetime objects, string datetime formats, or pandas dataframes/series (the assumption is sufficient in most cases).
The datetime object supports replacing arguments with values of our choice. The attributes provided by datetime.datetime and can be replaced include year, month, day, hour, minute, second, microsecond, and tzinfo (time zone information).
If we want to strip the second in datetime, we simply set the second argument to zero. Here are some examples.
from datetime import datetime time_now = datetime.now() print(time_now, "<-- datetime now - date, time") time_now_sec = time_now.replace(second=0) print(time_now_sec, "<-- second removed") time_now_sec1 = time_now.replace(second=0, microsecond=0) print(time_now_sec1, "<-- second and microsecond removed")
2022-08-11 16:07:29.593771 <-- datetime now - date, time 2022-08-11 16:07:00.593771 <-- second removed 2022-08-11 16:07:00 <-- second and microsecond removed
In the above code, we were able to set seconds and/or microseconds to zero and, therefore, effectively remove it/them from the datetime object.
Suppose, instead of simply truncating, we round off the datetime value to the nearest minute – if seconds<30, we set it to zero, otherwise, set it to zero and increase minutes by 1.
from datetime import datetime, timedelta def minute_round(dt): # Round to the nearest minute. If second<30 set it to zero and leave minutes # unchanges. Otherwise set seconds to zero and increase minutes by 1. return (dt.replace(second=0, microsecond=0, hour=dt.hour) +timedelta(minutes=dt.second//30)) # second at 30 time1 = datetime(2021, 3, 29, 14, 26, 30) print("time2 -->", time1) print("rounded time2 -->", minute_round(time1)) # second determines by current time time2 = datetime.now() print("time2 -->", time2) print("rounded time2 -->", minute_round(time2)) # second at 38 - above 30 seconds time3 = datetime(2022, 6, 12, 8, 7, 38, 5679) print("time3 -->", time3) print("rounded time3 -->", minute_round(time3)) # second at 21 - under 30 seconds time4 = datetime(2022, 11, 28, 12, 12, 21, 5679) print("time4 -->", time4) print("rounded time4 -->", minute_round(time4))
time2 --> 2021-03-29 14:26:30 rounded time2 --> 2021-03-29 14:27:00 time2 --> 2022-08-11 16:32:20.940362 rounded time2 --> 2022-08-11 16:32:00 time3 --> 2022-06-12 08:07:38.005679 rounded time3 --> 2022-06-12 08:08:00 time4 --> 2022-11-28 12:12:21.005679 rounded time4 --> 2022-11-28 12:12:00
The function minute_round() sets seconds and microseconds to zero, retains hour as is, and timedelta rounds off seconds into the nearest minute.
When dealing with datetime on string format, you must parse it before using replace to remove seconds. Parsing a string into datetime is achieved using <str>.strptime(<obj>, <format>) function.
from datetime import datetime str_dt1 = "2022-06-30 12:06:34" str_dt1_sec = datetime.strptime(str_dt1, "%Y-%m-%d %H:%M:%S").replace(second=0, microsecond=0) print(str_dt1_sec)
The code snippet above does two things – change the string str_dt1 into a datetime object using strptime() and then, as before, use replace() to set seconds and microseconds to zero.
If you want to round off seconds, convert the string to datetime and proceed as before by calling the minute_round() function.
Sometimes strptime() function fails to parse some strings to datetime. If you find this limitation problematic based on your task, you can use the dateparser package instead (you might have to install the library before using it).
The package contains the parse() function, which can parse strings more efficiently than strptime(). Here are some examples.
from dateparser import parse from datetime import datetime print("Now: ", datetime.now()) # string datetime str_dt2 = "2 days ago at 11:00:06" # parse string using parse() function str_dt2_parsed = parse(str_dt2) print(str_dt2) print(str_dt2_parsed) str_dt3 = "Jan 10, 2022, 10:37:57am" #parse string and remove seconds str_dt3_parsed = parse(str_dt3). replace(second=0, microsecond=0) print(str_dt3_parsed)
Now: 2022-08-11 17:01:16.805044 2 days ago at 11:00:06 2022-08-09 11:00:06 2022-01-10 10:37:00
The function parse() returns a datetime object. Once we have that, we can remove seconds as we did before.
Python pandas is a popular library used for data manipulation and analysis. This section covers removing seconds in pandas datetime objects on dataframes or series. We will save the following data as “example.csv” and use it in the examples that follow.
|2022-09-09 10:10:12||Jan 12, 2021 at 10am|
|2019-08-16 13:01:57||2022-01-29 14:00:58|
|1987/12/31 11:59:58||In 10 days|
import pandas as pd from dateparser import parse from datetime import datetime # Load example.csv df = pd.read_csv("example.csv") print("before parsing:\n", df.dtypes)
Output: before parsing: Dates1 object Dates2 object dtype: object
In the above code, we loaded example.csv and checked the data types for the two columns. At this point, the two columns are just objects (strings).
In the next step, we parse the strings into datetime. The inbuilt datetime module in Python can handle the parsing of Dates1 but not Dates2. We will use dateparse.parse() to pass Dates2.
Once the strings are passed to datetime, seconds are removed.
print("Now", datetime.now()) # convert Dates1 to pandas datetime and remove seconds with lambda function df["Dates1"] = pd.to_datetime(df["Dates1"], format="%Y-%m-%d %H:%M").map(lambda x: x.replace(second=0, microsecond=0)) # parse Dates2 row by row and remove seconds df["Dates2"] = df["Dates2"].map(lambda x: parse(x).replace(second=0, microsecond=0)) print("after parsing:\n", df.dtypes) print(df)
Output (Formated for better viewing):
Now 2022-08-11 17:34:43.712168 after parsing: Dates1 datetime64[ns] Dates2 datetime64[ns] dtype: object
|0||2022-09-09 10:10:00||2021-01-12 10:00:00|
|1||2019-08-16 13:01:00||2022-01-29 14:00:00|
|2||1987-12-31 11:59:00||2022-08-21 17:34:00|
In this article, we have seen how to remove seconds in datetime by either truncating it or rounding it off. We also saw how to convert strings or pandas object into datetime (whenever possible, of course).