How to Add Hours to Current Time in Python

Adding hours and days to the python datetime

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

Add hours with datetime.timedelta(hours=1)

I solved the problem, for some reason datetime.timedelta(hours=1) has to be out of the "(" like this :

a = datetime.datetime.combine(date.today(),Hour)
b = a + datetime.timedelta(hours=1)

And not like this

b=datetime.datetime.combine(date.today() +datetime.timedelta(hours=1),Hour)

Add one hour forward to current time in Python

You can make computations using seconds from epoch:

import time
t0 = time.time() # now (in seconds)
t1 = t0 + 60*30  # now + 30 minutes
t2 = t0 + 60*60 # now + 60 minutes

for t in [t0,t1,t2]:
print time.strftime("%I %M %p",time.localtime(t))

output

09 57 PM
10 27 PM
10 57 PM

if you want to round the time to the previous half-hour, add this line:

t0 -= t0 % (30*60) # round down to previous half-hour

Adding hours to the current time in Python

If it's a full date-time, you can use the timedelta object:

time_in_four_hours = current_time + timedelta(hours=4)

how to add x number of hours to datetime.datetime() in python

Use datetime.timedelta:

import datetime

d = datetime.datetime(2021, 11, 19, 17, 6, 45)
t = datetime.timedelta(hours=8)

d+t

output: datetime.datetime(2021, 11, 20, 1, 6, 45)

add 2 hours in current time in Python and print the time in timestamp

thanks to all of you, though this worked for me

start_at = 2
hours_from_now = int(str(time.time() + start_at * 60 * 60)[0:10]) * 1000


Related Topics



Leave a reply



Submit