pythondatetime

Expand date to the beginning and end datetime for the day


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?


Solution

  • 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)