Ilya
Ilya

Reputation: 363

Adding hours and days to the python datetime

I have a string in the following format

2021-05-06 17:30

How do I convert this to a python datetime and add a certain number of hours (e.g 4 hours)?

I also need to add a certain number of days to the string 2021-05-06

Upvotes: 3

Views: 6800

Answers (3)

Elisha Senoo
Elisha Senoo

Reputation: 3594

Use the timedelta method available on datetime object to add days, hours, minutes or seconds to the date.

from datetime import datetime, timedelta

additional_hours = 4
additional_days = 2

old_date = datetime.strptime('2021-05-06 17:30', '%Y-%m-%d %H:%M')
new_date = old_date + timedelta(hours=additional_hours, days=additional_days)

print(new_date)

Upvotes: 2

G.Young
G.Young

Reputation: 141

from datetime import datetime
from datetime import timedelta

origin_date = datetime.strptime("2021-05-06 17:30","%Y-%m-%d %H:%M")
three_hour_later = origin_date + timedelta(hours=3)

print(datetime.strftime(three_hour_later,"%Y-%m-%d %H:%M"))

Please check this link. https://docs.python.org/3/library/datetime.html

Upvotes: 5

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477686

You can first parse the string to a datetime object, and then use a timedelta to add days, hours, etc. to the item.

from datetime import datetime, timedelta

dt = datetime.strptime('2021-05-06 17:30', '%Y-%m-%d %H:%M')
print(dt + timedelta(hours=4))

Upvotes: 7

Related Questions