How to truncate the time on a datetime object?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 Question
00:32 Accepted answer (Score 508)
00:57 Answer 2 (Score 96)
01:17 Answer 3 (Score 48)
01:59 Answer 4 (Score 26)
02:50 Thank you
--
Full question
https://stackoverflow.com/questions/5476...
Answer 3 links:
[datetime.combine()]: https://docs.python.org/3/library/dateti...
[the ]: https://stackoverflow.com/a/5476114/4279
[datetime]: http://bugs.python.org/issue15443
[How do I get the UTC time of “midnight” for a given timezone?]: https://stackoverflow.com/a/11236372/427...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime
#avk47
ACCEPTED ANSWER
Score 545
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 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 = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)
ANSWER 2
Score 101
Use a date not a datetime if you dont care about the time.
>>> now = datetime.now()
>>> now.date()
datetime.date(2011, 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)
ANSWER 3
Score 27
To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:
>>> from datetime import datetime, time
>>> dt = datetime.utcnow()
>>> dt.date()
datetime.date(2015, 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?
ANSWER 4
Score 26
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)