How to truncate the time on a datetime object?
I think this is what you're looking for...
import datetime dt = datetime.datetime.now() dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copydtdatetime.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
2011, 3, 29)d_truncated = datetime.date(dt.year, dt.month, dt.day) d_truncateddatetime.date(
Four years later: another way, avoiding
I know the accepted answer from four years ago works, but this seems a tad lighter than using
dt = datetime.date.today()dt = datetime.datetime(dt.year, dt.month, dt.day)
- When you create a
datetimeobject 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 = datetime.datetime.now()