Python datetime - setting fixed hour and minute after using strptime to get day,month,year

user1678031 picture user1678031 · Sep 18, 2012 · Viewed 205.8k times · Source

I've successfully converted something of 26 Sep 2012 format to 26-09-2012 using:

datetime.strptime(request.POST['sample_date'],'%d %b %Y')

However, I don't know how to set the hour and minute of something like the above to 11:59. Does anyone know how to do this?

Note, this can be a future date or any random one, not just the current date.

Answer

nneonneo picture nneonneo · Sep 18, 2012

Use datetime.replace:

from datetime import datetime
date = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdate = date.replace(hour=11, minute=59)