Home > Enterprise >  replace minute on a datetime object
replace minute on a datetime object

Time:10-16

I try to replace the minute value on a datetime object but it is not working. It still write the actual time.

time = datetime.now()
time = time.replace(second=0, microsecond=0)
if time.minute in [0, 1, 2]:
    time.replace(minute=0)
elif time.minute in [15, 16, 17]:
    time.replace(minute=15)
elif time.minute in [30, 31, 32]:
    time.replace(minute=30)
elif time.minute in [45, 46, 47]:
    time.replace(minute=45)
elif time.minute < 15:
    time.replace(minute=15)
elif time.minute < 30:
    time.replace(minute=30)
elif time.minute < 45:
    time.replace(minute=45)
elif time.minute < 59:
    time.replace(minute=0)

CodePudding user response:

The issue is that you're not saving any the actual results of time.replace() into any variable. It is replacing the minutes, but when you call the variable 'time' again, you still see the old result as it is not saved. You can either save it in the same variable named 'time' or save the .replace() into a new one.

For each if (taking the first one as an example), try:

time = time.replace(minute=0)

Or

new_variable = time.replace(minute=0)

When you call the new variable, change should've applied.

  • Related