
Hi Python Devs,
Are you looking for a way to add minutes to a datetime in Python? You're in the right place! This tutorial explains how to easily add minutes to any date or time object using Python’s datetime and dateutil.relativedelta libraries.
This guide covers both scenarios—adding minutes to a specific date and adding minutes to the current datetime. Whether you're working with a timestamp string, datetime object, or DataFrame, these examples are very helpful for real-world projects.
So let’s dive into the code examples step-by-step.
Example 1: Python Add Minutes to DateTime
main.py
from datetime import datetime
from dateutil.relativedelta import relativedelta
myDateString = "2022-09-01"
myDate = datetime.strptime(myDateString, "%Y-%m-%d")
addMinutesNumber = 20
newDate = myDate + relativedelta(minutes=addMinutesNumber)
print("Old Date :")
print(myDate)
print("New Date :")
print(newDate)
Output:
Old Date : 2022-09-01 00:00:00 New Date : 2022-09-01 00:20:00
Example 2: Python Add Minutes to Current DateTime
main.py
from datetime import datetime
from dateutil.relativedelta import relativedelta
myDate = datetime.today()
addMinutesNumber = 20
newDate = myDate + relativedelta(minutes=addMinutesNumber)
print("Old Date :")
print(myDate)
print("New Date :")
print(newDate)
Output:
Old Date : 2022-09-16 04:13:19.232998 New Date : 2022-09-16 04:33:19.232998
This is a simple and effective way to manipulate datetime values in Python. Whether you're creating logs, scheduling tasks, or working with time-based data, adding time offsets like minutes is a fundamental technique in time management with Python.
Happy Pythonic Coding!
🧠 FAQ - Python DateTime Minutes Additions
- Q: How do I add minutes to a datetime in Python?
A: You can usedatetime + timedelta(minutes=5)or userelativedeltafor more advanced scenarios. - Q: What is the best way to add time to a date string in Python?
A: First convert the string usingstrptime(), then use timedelta or relativedelta to add time. - Q: Can I use pandas to add minutes to datetime?
A: Yes! Usedf['datetime'] + pd.Timedelta(minutes=5). - Q: How to add 15 minutes to now() in Python?
A: Usedatetime.now() + timedelta(minutes=15). - Q: Which library supports flexible date manipulation in Python?
A:dateutil.relativedeltais perfect for flexible time manipulation like months, minutes, years, etc.