python datetime的加減操作
阿新 • • 發佈:2019-01-08
python時間操作有很多,今天根據業務需求需要做時間的加減操作,找了很久沒找到。在此記錄,以防忘記
from datetime import timedelta
timedelta可以做時間的加減操作
一下是官方的解釋
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. Only days, seconds and microseconds are stored internally. Arguments are converted to those units: A millisecond is converted to 1000 microseconds. A minute is converted to 60 seconds. An hour is converted to 3600 seconds. A week is converted to 7 days. and days, seconds and microseconds are then normalized so that the representation is unique, with 0 <= microseconds < 1000000 0 <= seconds < 3600*24 (the number of seconds in one day) -999999999 <= days <= 999999999 If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond. If no argument is a float, the conversion and normalization processes are exact (no information is lost). If the normalized value of days lies outside the indicated range, OverflowError is raised. Note that normalization of negative values may be surprising at first. For example, >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) >>> (d.days, d.seconds, d.microseconds) (-1, 86399, 999999)
具體用法:
time = timedelta(minutes=1)datetime.now + time
minutes處可以填寫單位,後邊關聯的是具體的時間,然後和你需要的時間直接進行加減操作