[Django]-Adding hours and days to the python datetime

5πŸ‘

βœ…

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

πŸ‘€G.Young

7πŸ‘

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))

2πŸ‘

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)
πŸ‘€Elisha Senoo

Leave a comment