Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Calculate last quarter hour of current time

How do I round the time to last quarter hour for the current time. I am able to find the last quarter hour minute, however, not able to fit this into the correct time format.

import datetime
import time

time = datetime.datetime.now()
last_quarter_minute = 15*(time.minute//15)

current_time = time.strftime("%Y/%m/%d %H:%M")

print last_quarter_minute
print current_time

Ideally, I want to be able to compare the time I get from a log, to the last quarter time.

like image 909
Mir S Mehdi Avatar asked Oct 22 '25 14:10

Mir S Mehdi


1 Answers

You need to replace minute part of the time, using datetime.datetime.replace (returns a new datetime object with the specifieid field replaced):

>>> time.strftime("%Y/%m/%d %H:%M")
'2016/05/13 12:57'
>>> time.replace(minute=last_quarter_minute).strftime("%Y/%m/%d %H:%M")
'2016/05/13 12:45'

To be more precise, you need to also set second, microsecond also.

like image 148
falsetru Avatar answered Oct 25 '25 02:10

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!