Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add delta to python datetime.time?

From:

http://docs.python.org/py3k/library/datetime.html#timedelta-objects

A timedelta object represents a duration, the difference between two dates or times.

So why i get error with this:

>>> from datetime import datetime, timedelta, time >>> datetime.now() + timedelta(hours=12) datetime.datetime(2012, 9, 17, 6, 24, 9, 635862) >>> datetime.now().date() + timedelta(hours=12) datetime.date(2012, 9, 16)  >>> datetime.now().time() + timedelta(hours=12) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' 
like image 338
xliiv Avatar asked Sep 16 '12 16:09

xliiv


People also ask

How do you add 1 second to time in Python?

Use the timedelta() class from the datetime module to add seconds to datetime, e.g. result = dt + timedelta(seconds=24) .

How do I add time to a datetime?

Add Days to datetime Object If we want to add days to a datetime object, we can use the timedelta() function of the datetime module.

How do you add and subtract datetime in Python?

For adding or subtracting date, we use something called timedelta() function which can be found under datetime class. It is used to manipulate date, and we can perform an arithmetic operations on date like adding or subtract. timedelta is very easy and useful to implement.


2 Answers

datetime.time objects do not support addition with datetime.timedeltas.

There is one natural definition though, clock arithmetic. You could compute it like this:

import datetime as dt now = dt.datetime.now() delta = dt.timedelta(hours = 12) t = now.time() print(t) # 12:39:11.039864  print((dt.datetime.combine(dt.date(1,1,1),t) + delta).time()) # 00:39:11.039864 

dt.datetime.combine(...) lifts the datetime.time t to a datetime.datetime object, the delta is then added, and the result is dropped back down to a datetime.time object.

like image 52
unutbu Avatar answered Sep 30 '22 18:09

unutbu


All the solutions above are too complicated, OP had already shown that we can do calculation between datetime.datetime and datetime.timedelta, so why not just do:

(datetime.now() + timedelta(hours=12)).time()

like image 27
ssword Avatar answered Sep 30 '22 18:09

ssword