Skip to content

Instantly share code, notes, and snippets.

@comargo
Last active August 1, 2017 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save comargo/16c049f14381f7789c8a1de239ad133e to your computer and use it in GitHub Desktop.
Save comargo/16c049f14381f7789c8a1de239ad133e to your computer and use it in GitHub Desktop.
Python ceil up or floor down datetime object to given resolution (not exceeding one day, with one second granularity)
from datetime import timedelta
def ceil_dt(dt, res):
# how many secs have passed this day
nsecs = dt.hour*3600 + dt.minute*60 + dt.second + dt.microsecond*1e-6
delta = res.seconds - nsecs % res.seconds
if delta == res.seconds:
delta = 0
return dt + datetime.timedelta(seconds=delta)
def floor_dt(dt, res):
# how many secs have passed this day
nsecs = dt.hour*3600 + dt.minute*60 + dt.second + dt.microsecond*1e-6
delta = nsecs % res.seconds
return dt - datetime.timedelta(seconds=delta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment