python - What is the best way to handle datetime value overflow -
i attempting build program handle alerts. want able handle specific dates 8/23/2015 7:00 , relative dates 5 days , 7 hours now. specific dates fine relative dates if try , add 5 days , 7 hours date time can overflow values intended spot
import datetime dt = datetime.datetime.now() dayslater = 5 hourslater = 7 minuteslater = 30 alarmtime = datetime.datetime(dt.year, dt.month, dt.day + dayslater, dt.hour + hourslater, dt.minute + minuteslater, 0,0)
this fine if dayslater 40 days overflow value. did set simple
if hours >= 24: hours -= 24 days++
however won't work overflowing months length in days isn't consistent.
use datetime.timedelta()
object , leave calculations datetime
library:
import datetime delta = datetime.timedelta(days=dayslater, hours=hourslater, minutes=minuteslater) alarmtime = datetime.datetime.now() + delta
demo:
>>> import datetime >>> dt = datetime.datetime.now() >>> dayslater = 5 >>> hourslater = 7 >>> minuteslater = 30 >>> delta = datetime.timedelta(days=dayslater, hours=hourslater, minutes=minuteslater) >>> delta datetime.timedelta(5, 27000) >>> dt datetime.datetime(2015, 7, 23, 21, 4, 59, 987926) >>> dt + delta datetime.datetime(2015, 7, 29, 4, 34, 59, 987926)
note how hours carried on next day (from 21:04 04:34), , date went 23rd 29th. did not have worry 'overflow' here.
this continues work @ month boundaries, @ year boundaries, , in leap years, february 29th:
>>> datetime.datetime(2015, 7, 26, 22, 42) + delta datetime.datetime(2015, 8, 1, 6, 12) >>> datetime.datetime(2015, 12, 26, 22, 42) + delta datetime.datetime(2016, 1, 1, 6, 12) >>> datetime.datetime(2016, 2, 23, 22, 42) + delta datetime.datetime(2016, 2, 29, 6, 12)
Comments
Post a Comment