Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ rewrite DATETRUNC #865

Closed
joocer opened this issue Feb 13, 2023 · 1 comment
Closed

✨ rewrite DATETRUNC #865

joocer opened this issue Feb 13, 2023 · 1 comment

Comments

@joocer
Copy link
Contributor

joocer commented Feb 13, 2023

def datetrunc_fast(date, unit):
if unit == 'second':
return date.replace(microsecond=0)
elif unit == 'minute':
seconds_per_minute = 60
full_minutes, remainder = divmod((date - datetime.datetime(1970, 1, 1)).total_seconds(), seconds_per_minute)
return date - datetime.timedelta(seconds=remainder)
elif unit == 'hour':
seconds_per_hour = 60 * 60
full_hours, remainder = divmod((date - datetime.datetime(1970, 1, 1)).total_seconds(), seconds_per_hour)
return date - datetime.timedelta(seconds=remainder)
elif unit == 'day':
days_per_day = 1
full_days, remainder = divmod((date - datetime.datetime(1970, 1, 1)).days, days_per_day)
return date - datetime.timedelta(days=remainder)
elif unit == 'week':
days_per_week = 7
full_weeks, remainder = divmod((date - datetime.datetime(1970, 1, 1)).days, days_per_week)
return date - datetime.timedelta(days=remainder)
elif unit == 'month':
full_months, remainder = divmod(12 * (date.year - 1970) + (date.month - 1), 12)
return date.replace(year=date.year - full_months, month=1)
elif unit == 'quarter':
full_quarters, remainder = divmod(4 * (date.year - 1970) + (date.month - 1) // 3, 4)
return date.replace(year=date.year - full_quarters, month=((remainder * 3) % 12) + 1)
elif unit == 'year':
full_years, remainder = divmod(date.year - 1970, 1)
return date.replace(year=date.year - full_years)
else:
raise ValueError("Invalid unit: {}".format(unit))

@joocer
Copy link
Contributor Author

joocer commented Feb 13, 2023

It's not a common function and isn't a performance concern, but replacing it removes a third-party piece of code and marginally improves performance.

50%   0.8710ms, 95%   1.5160ms, 99%   2.0860ms, 99.99%  42.8863ms,  100000 cycles of first_party
50%   1.3250ms, 95%   2.3880ms, 99%   2.9770ms, 99.99%  47.4730ms,  100000 cycles of third_party

@joocer joocer closed this as completed Feb 13, 2023
joocer added a commit that referenced this issue Feb 13, 2023
joocer added a commit that referenced this issue Feb 14, 2023
joocer added a commit that referenced this issue Feb 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant