How to add delta to python datetime.time?

后端 未结 5 1967
别那么骄傲
别那么骄傲 2020-11-27 06:46

From:

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

A timedelta object represents a duration, the difference between two

5条回答
  •  时光取名叫无心
    2020-11-27 07:00

    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.

提交回复
热议问题