python - How to truncate the time on a datetime object?

ID : 10334

viewed : 24

Tags : pythondatetimepython

Top 5 Answer for python - How to truncate the time on a datetime object?

vote vote


I think this is what you're looking for...

>>> import datetime >>> dt = >>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy >>> dt datetime.datetime(2011, 3, 29, 0, 0) 

But if you really don't care about the time aspect of things, then you should really only be passing around date objects...

>>> d_truncated =, dt.month, >>> d_truncated, 3, 29) 
vote vote


Use a date not a datetime if you dont care about the time.

>>> now = >>>, 3, 29) 

You can update a datetime like this:

>>> now.replace(minute=0, hour=0, second=0, microsecond=0) datetime.datetime(2011, 3, 29, 0, 0) 
vote vote


Four years later: another way, avoiding replace

I know the accepted answer from four years ago works, but this seems a tad lighter than using replace:

dt = dt = datetime.datetime(dt.year, dt.month, 


  • When you create a datetime object without passing time properties to the constructor, you get midnight.
  • As others have noted, this assumes you want a datetime object for later use with timedeltas.
  • You can, of course, substitute this for the first line: dt =
vote vote


You cannot truncate a datetime object because it is immutable.

However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo:

newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0) 
vote vote


To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:

>>> from datetime import datetime, time >>> dt = datetime.utcnow() >>>, 2, 3) >>> datetime.combine(dt, time.min) datetime.datetime(2015, 2, 3, 0, 0) 

The advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support.

tzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone?

Top 3 video Explaining python - How to truncate the time on a datetime object?