python time offset

后端 未结 1 954
臣服心动
臣服心动 2021-02-05 03:56

How can I apply an offset on the current time in python?

In other terms, be able to get the current time minus x hours and/or minus m minutes and/or minus s secondes a

相关标签:
1条回答
  • 2021-02-05 04:47

    Use a datetime.datetime(), then add or subtract datetime.timedelta() instances.

    >>> import datetime
    >>> t = datetime.datetime.now()
    >>> t - datetime.timedelta(hours=1, minutes=10)
    datetime.datetime(2012, 12, 26, 17, 18, 52, 167840)
    

    timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method:

    >>> t = datetime.time(1, 2)
    >>> dt = datetime.datetime.combine(datetime.date.today(), t)
    >>> dt
    datetime.datetime(2012, 12, 26, 1, 2)
    >>> dt -= datetime.timedelta(hours=5)
    >>> dt.time()
    datetime.time(20, 2)
    
    0 讨论(0)
提交回复
热议问题