django python date time set to midnight


I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same)

end_date = lastItem.pub_date

currently the end date is 2002-01-11 12:34:56
What do I need to do to get this to change it to 00:00:00?

i tried:

end_date.hour = '00'

but got: ‘datetime.datetime’ object attribute ‘time’ is read-only

Asked By: Designer023



Are you sure you don’t want to use dates instead of datetimes? If you’re always setting the time to midnight, you should consider using a date. If you really want to use datetimes, here’s a function to get the same day at midnight:

def set_to_midnight(dt):
    midnight = datetime.time(0)
    return datetime.datetime.combine(, midnight)
Answered By: Gavin Wahl

Try this:

import datetime
pub = lastItem.pub_date
end_date = datetime.datetime(pub.year, pub.month,
Answered By: mipadi

datetime instance attributes like year, month, day, hour, etc are read-only, so you just have to create a new datetime object and assign it to end_date.

Answered By: jan zegan

Using datetimes’s “combine” with the time.min and time.max will give both of your datetimes.
For example:

from datetime import date, datetime, time
pub_date =
min_pub_date_time = datetime.combine(pub_date, time.min) 
max_pub_date_time = datetime.combine(pub_date, time.max)  

Result with pub_date of 6/5/2013:

min_pub_date_time -> datetime.datetime(2013, 6, 5, 0, 0)

max_pub_date_time -> datetime.datetime(2013, 6, 5, 23, 59, 59, 999999)

Answered By: raman

For tz-aware dates it should be:

datetime.combine(, datetime.min.time(), dt.tzinfo)
Answered By: Antony Hatchkins