4

Based on the current time (datetime.now()) I want to expand this to cover the whole days time.

Right now I have been using:

start = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
end = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

Problem is that this is 24 hours from the current date. If it is 12pm noon that means it should only look back 12 hours as I want to search for the current days records.

How can I accomplish this in Python?

ComputerLocus
  • 3,448
  • 10
  • 47
  • 96
  • http://stackoverflow.com/questions/5476065/truncate-python-datetime – NightShadeQueen Jul 17 '15 at 16:34
  • @NightShadeQueen so essentially set the start time to the truncated version of datetime and then use the current time for the end range. That should work. – ComputerLocus Jul 17 '15 at 16:38
  • related: [Python: Given the current time in UTC, how do you determine the start and end time of the day in a particular timezone?](http://stackoverflow.com/a/25605133/4279) – jfs Jul 18 '15 at 19:57

4 Answers4

9

I hope this makes sense, I just gave very descriptive variable names

from datetime import datetime
from datetime import timedelta

now = datetime.now()
start_of_day = datetime(now.year,now.month,now.day)
delta_since_start_of_day = now - start_of_day
delta_till_end_of_day = timedelta(days=1) - delta_since_start_of_day
end_of_day = start_of_day + timedelta(days=1)
fivetentaylor
  • 1,277
  • 7
  • 11
9

Here's another solution that directly resets the time - no math required. Uses datetime.replace():

now = datetime.now()
day_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
day_end = day_start + timedelta(hours=24)
Halogen
  • 551
  • 6
  • 11
5

It seems you could accomplish what you wish like so:

from datetime import datetime, time

now = datetime.now()
start = datetime.combine(now, time.min)  # datetime.datetime(2021, 11, 5, 0, 0)
end = datetime.combine(now, time.max)  # datetime.datetime(2021, 11, 5, 23, 59, 59, 999999)

No need for maths, replacing, timedeltas.

cegas
  • 2,823
  • 3
  • 16
  • 16
  • This should be the accepted answer. It is so much cleaner to read and easier to understand what the code is doing and why. – DukeSilver Aug 28 '23 at 17:39
-1

I just use datetime.time.max in this way:

now = datetime.now()
day_end = datetime.datetime.combine(now, datetime.time.max)
sabrina
  • 1,567
  • 2
  • 12
  • 15