Add hours with datetime.timedelta(hours=1)

Viewed 1745

I saw in a related post that you cant add with .timedelta less than 24 hours but i need to really add a hour to my time, my code is this:

Hour =df['Hour'].values[0]
16:42:00
The column Hour is a datetime.time

And im trying to add one hour like this :

from datetime import date
HourPlus=datetime.datetime.combine(date.today() +datetime.timedelta(hours=1),Hour)

But only works if i add days=1 and not hours, how can i solve this ?

from datetime import date
HourPlus=datetime.datetime.combine(date.today() +datetime.timedelta(days=1),Hour)
2021-04-14 16:42:00
4 Answers

pandas Timedelta() works

df = pd.DataFrame(pd.date_range("1-apr-2021", freq="H", periods=12), columns=["hour"])

df.assign(plus1=df["hour"] + pd.Timedelta(hours=1))

output

                  hour               plus1
0  2021-04-01 00:00:00 2021-04-01 01:00:00
1  2021-04-01 01:00:00 2021-04-01 02:00:00
2  2021-04-01 02:00:00 2021-04-01 03:00:00
3  2021-04-01 03:00:00 2021-04-01 04:00:00
4  2021-04-01 04:00:00 2021-04-01 05:00:00
5  2021-04-01 05:00:00 2021-04-01 06:00:00
6  2021-04-01 06:00:00 2021-04-01 07:00:00
7  2021-04-01 07:00:00 2021-04-01 08:00:00
8  2021-04-01 08:00:00 2021-04-01 09:00:00
9  2021-04-01 09:00:00 2021-04-01 10:00:00
10 2021-04-01 10:00:00 2021-04-01 11:00:00
11 2021-04-01 11:00:00 2021-04-01 12:00:00

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)

The heart of the problem in the question is that

date.today() +datetime.timedelta(hours=1)

fails to add an hour because datetime.date is a date not a datetime. So, adding an hour to the date doesn't change the date.

You need to have a datetime.datetime object to meaningfully add an hour.

>>> import datetime 
>>> x = datetime.date.today()
>>> x
datetime.date(2021, 4, 13)
>>> x + datetime.timedelta(hours=1)
datetime.date(2021, 4, 13)
>>> y = datetime.datetime.today()
>>> y
datetime.datetime(2021, 4, 13, 14, 32, 41, 989496)
>>> y + datetime.timedelta(hours=1)
datetime.datetime(2021, 4, 13, 15, 32, 41, 989496)
>>> 

Using datetime.now() instead of date.today() keeps the time component.

import datetime as dt

nw = dt.datetime.now()
print(nw)
print(nw + dt.timedelta(hours=1))

Related