Borislav Hadzhiev
Wed Jun 22 2022·2 min read
Photo by Raychan
Use the timedelta()
class from the datetime
module to add seconds to
datetime, e.g. result = dt + timedelta(seconds=24)
. The timedelta
class can
be passed a seconds
argument and adds the specified number of seconds to the
datetime.
from datetime import datetime, timedelta # ✅ add seconds to datetime dt = datetime(2023, 9, 24, 9, 30, 35) print(dt) # 👉️ 2023-09-24 09:30:35 result = dt + timedelta(seconds=24) print(result) # 👉️ 2023-09-24 09:30:59 # ------------------------------ # ✅ add seconds to current time now = datetime.today() print(now) # 👉️ 2022-06-22 11:56:16.347314 result_2 = now + timedelta(seconds=15) print(result_2) # 👉️ 2022-06-22 11:56:51.620548
09:30:13
scroll down to the last code snippet.Make sure to import the datetime
and
timedelta
classes from the datetime
module.
The first example uses the
datetime
class to create a datetime
object.
We passed values for the year
, month
, day
, hour
, minute
and second
arguments.
Once we have a datetime
object, we can use the timedelta
class to add
seconds to it.
from datetime import datetime, timedelta # ✅ add seconds to datetime dt = datetime(2023, 9, 24, 9, 30, 35) print(dt) # 👉️ 2023-09-24 09:30:35 result = dt + timedelta(seconds=24) print(result) # 👉️ 2023-09-24 09:30:59
The second example adds seconds to the current time.
from datetime import datetime, timedelta now = datetime.today() print(now) # 👉️ 2022-06-22 11:56:16.347314 result_2 = now + timedelta(seconds=15) print(result_2) # 👉️ 2022-06-22 11:56:51.620548
The datetime.today() method returns the current local datetime.
datetime
object because it automatically rolls over the minutes, hours, days, months and years if necessary.This wouldn't be possible if we only had the time component. For example,
11:59:30PM
+ 50
seconds would raise an exception.
datetime.combine
method to combine the time with the current (or some other) date and get a datetime
object.from datetime import datetime, date, timedelta, time t = time(9, 30, 13) print(t) # 👉️ 09:30:13 result = datetime.combine(date.today(), t) + timedelta(seconds=27) print(result) # 👉️ 2022-06-22 09:30:40 only_t = result.time() print(only_t) # 👉️ 09:30:40
The
datetime.combine
method takes a date
and time
as arguments and returns a new datetime
object by combining them.
Once we get a datetime
object, we can use the timedelta
class to add seconds
to it.
Use the time()
method on the datetime
object if you only need to extract the
time after the operation.
from datetime import datetime, date, timedelta, time t = time(9, 30, 13) print(t) # 👉️ 09:30:13 result = datetime.combine(date.today(), t) + timedelta(seconds=27) print(result) # 👉️ 2022-06-22 09:30:40 # ✅ only get updated time only_t = result.time() print(only_t) # 👉️ 09:30:40
The datetime.time method returns a time object with the same hour, minute, second and millisecond.