How to use Python to calculate time

前端 未结 5 1010
傲寒
傲寒 2021-02-05 22:32

I want to write python script that acts as a time calculator.

For example:

Suppose the time is now 13:05:00

I want to add 1 hour, 23 minutes, and 10 seco

5条回答
  •  生来不讨喜
    2021-02-05 22:52

    datetime.timedelta is designed for fixed time differences (e.g. 1 day is fixed, 1 month is not).

    >>> import datetime
    >>> t = datetime.time(13, 5)
    >>> print t
    13:05:00
    >>> now = datetime.datetime.now()
    >>> print now
    2009-11-17 13:03:02.227375
    >>> print now + datetime.timedelta(hours=1, minutes=23, seconds=10)
    2009-11-17 14:26:12.227375
    

    Note that it doesn't make sense to do addition on just a time (but you can combine a date and a time into a datetime object, use that, and then get the time). DST is the major culprit. For example, 12:01am + 5 hours could be 4:01am, 5:01am, or 6:01am on different days.

提交回复
热议问题