John Titus Jungao John Titus Jungao - 16 days ago 5
Python Question

Python: Adding Float formatted time to datetime value

I want to add a randomly generated time value to an existing

datetime
object. Now, the time value that I have is a float. For example, I want to add
4.1326742
hours to
'2016-11-17'
. How do I do this? Thanks.

Answer

You just need to construct a timedelta and add it:

>>> import datetime
>>> d = datetime.datetime(2016, 11, 17)
>>> delta = datetime.timedelta(hours=4.1326742)
>>> d + delta
datetime.datetime(2016, 11, 17, 4, 7, 57, 627120)
Comments