Last active
August 1, 2017 21:28
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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