Reputation: 1949
I have multiple datetime objects, for example:
>>a
datetime.datetime(2009, 11, 1, 0, 0)
I want to keep date unchanged and alter time to zeros (three digits in time):
>>b
datetime.datetime(2009, 11, 1, 0, 0, 0)
Probably simple but i can't figure it out
EDIT: For some reason a zero for seconds doesnt work. It does not matter, it works with a 1:
>>a
datetime.datetime(2009, 11, 1, 0, 0)
>>b = datetime.datetime.combine(a.date(), datetime.time(0,0,0))
>>b
datetime.datetime(2009, 11, 1, 0, 0)
>>b = datetime.datetime.combine(a.date(), datetime.time(0,0,1))
>>b
datetime.datetime(2009, 11, 1, 0, 0, 1)
Upvotes: 2
Views: 5404
Reputation: 9727
datetime.datetime(2009, 11, 1, 0, 0)
and datetime.datetime(2009, 11, 1, 0, 0, 0)
create the same datetime objects. See https://docs.python.org/2/library/datetime.html#datetime.datetime for details.
If you have non-zero hours, minutes or seconds you can use replace
to make them zero:
dt = datetime.datetime(2009, 11, 1, 3, 15, 49)
dt.replace(hour=0, minute=0, second=0)
Upvotes: 0
Reputation: 506
import datetime
date_with_zeros = datetime.datetime(2009, 11, 1, 1, 0, 0).replace(hour=0, minute=0, second=0)
Just use replace.
Upvotes: 7
Reputation: 599470
It's a bit fiddly, but you can use combine
:
b = datetime.datetime.combine(a.date(), datetime.time(0,0,0))
Upvotes: 5