Is there any good idea to ceil or floor datetime in python3?

Viewed 3233
from datetime import datetime
roughtime = datetime(2018,1,1,5,2,1)

I want to floor roughtime as datetime.datetime(2018, 1, 1, 0, 0, 0) and also ceil roughtime as datetime.datetime(2018, 1, 2, 0, 0, 0).

Is there any convenient way to realize this? I know I can convert roughtime using matplotlib.dates.date2num. But I wonder if there are other ingenious ideas 

2 Answers

You can use replace function to replace the time part to make it floor and add one day to make it ceil

In [1]: import datetime

In [2]: def ceil(datetimeObj):
   ...:     return floor(datetimeObj) + datetime.timedelta(days=1)
   ...:

In [3]: def floor(datetimeObj):
   ...:     return datetimeObj.replace(second=0, hour=0, minute=0)
   ...:

In [4]: roughtime = datetime.datetime(2018,1,1,5,2,1)

In [5]: ceil(roughtime)
Out[5]: datetime.datetime(2018, 1, 2, 0, 0)

In [6]: floor(roughtime)
Out[6]: datetime.datetime(2018, 1, 1, 0, 0)

You can use the datetime.combine(date, time) to create new datetime object using given datetime.date and datetime.time.

Floor

from datetime import datetime
floored = datetime.combine(roughtime.date(), datetime.min.time())

Ceil

from datetime import datetime, timedelta

if roughtime.time() == datetime.min.time():
    ceiled = roughtime
else:
    ceiled = datetime.combine(roughtime.date()+timedelta(days=1), datetime.min.time())
  • Ceiling needs if..else statement since if you would ceil 2020-07-24 00:00:00 one would not expect to get 2020-07-25 00:00:00
  • ceiled = roughtime is okay (no need to make a copy), since datetime objects are immutable. (source)
Related