I am trying to convert default timezone datetime
to localtime
and round the time to 15min slots in Django views. I have the following roundTime function:
def roundTime(dt=None, dateDelta=timedelta(minutes=1)):
"""Round a datetime object to a multiple of a timedelta
dt : datetime.datetime object, default now.
dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
Stijn Nevens 2014 - Changed to use only datetime objects as variables
"""
roundTo = dateDelta.total_seconds()
if dt == None:
dt = datetime.now()
seconds = (dt - dt.min).seconds
# // is a floor division, not a comment on following line:
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + timedelta(0,rounding-seconds,-dt.microsecond)
And here is what I have tried so far:
mytime = roundTime(datetime.now(),timedelta(minutes=15)).strftime('%H:%M:%S') #works OK
mytime = datetime.strptime(str(mytime), '%H:%M:%S') #works OK
mytime = timezone.localtime(mytime)
But the last line gives me this error:
error: astimezone() cannot be applied to a naive datetime
And when I use:
local_time = timezone.localtime(timezone.now())
I do get the correct local time, but for some reason I'm unable to round the time by doing:
mytime = roundTime(local_time,timedelta(minutes=15)).strftime('%H:%M:%S')
which works with the datetime.now()
above.
I was able to come up with this not pretty but working code:
mytime = timezone.localtime(timezone.now())
mytime = datetime.strftime(mytime, '%Y-%m-%d %H:%M:%S')
mytime = datetime.strptime(str(mytime), '%Y-%m-%d %H:%M:%S')
mytime = roundTime(mytime,timedelta(minutes=15)).strftime('%H:%M:%S')
mytime = datetime.strptime(str(mytime), '%H:%M:%S')
Is there a better solution?