Bussiere
Bussiere

Reputation: 1154

Add hour and minute to a django DateTimeField already saved

Here is my model :

futureEventDate = models.DateTimeField(null=True, blank=True)

And now i'am setting futureEventDate :

eventSub.futureEventDate = datetime.datetime.strptime(
    formEvent["futureEventDate"], "%m/%d/%Y"
).date()

But now that it's done i would like to specify hour and minute to eventSub.futureEventDate.

How to do that ?

Upvotes: 1

Views: 919

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You can use .replace(..) for a datetime object to specify hours and minutes, for example:

eventSub.futureEventDate = datetime.datetime.strptime(
    formEvent["futureEventDate"], "%m/%d/%Y"
).replace(hour=14, minute=25)

This will thus retain the date, but change the time to 14:25. In case the original datetime object contains non-zero seconds, and/or microseconds, you can set these to 0 as well:

eventSub.futureEventDate = datetime.datetime.strptime(
    formEvent["futureEventDate"], "%m/%d/%Y"
).replace(hour=14, minute=25, second=0, microsecond=0)

Upvotes: 1

Related Questions