Hello i am to select data for a particular range of dates and would like to compare the same period with previous year. Any leads on how to go about it?
Thanks
Hello i am to select data for a particular range of dates and would like to compare the same period with previous year. Any leads on how to go about it?
Thanks
I have tried working on this but i get this error!
Callback error updating testDate.children
AttributeError: βstrβ object has no attribute βyearβ
Here is the code i am working with
import pandas as pd
import dash
import datetime as dt
import calendar
from dash import Dash, html, dcc, Input, Output
sales = pd.read_csv('sales_data.csv', parse_dates=['date'])
app = Dash(__name__)
app.layout = html.Div([
# Date Picker
html.Div([
dcc.DatePickerRange(
id='date_filter',
end_date_placeholder_text='End Date',
first_day_of_week=1,
month_format='MMMM Y',
minimum_nights=2,
persistence_type='session',
updatemode='singledate')], ),
html.Div([
html.Div([
html.Div(id='testDate'),
], className='card'),])
])
@app.callback(
Output('testDate', 'children'),
[Input('date_filter', 'start_date'),
Input('date_filter', 'end_date'),
]
)
def update_output(start_date, end_date):
if not start_date or not end_date:
raise dash.exceptions.PreventUpdate
else:
# Sales current year
cy_total_sales = sales[(sales['date'] >= start_date) & (sales['date'] <= end_date)]['sales'].sum()
# Time Delta
# cy_start_date = start_date
# cy_end_date = end_date
period = 12
# Previous Year corresponding start and end years
py_start_year = start_date.year + (start_date.month - 1 + period) // 12
py_end_year = end_date.year + (end_date.month - 1 + period) // 12
# Previous Year corresponding start and end months
py_start_month = (start_date.month - 1 + period) % 12 - 1
py_end_month = (end_date.month - 1 + period) % 12 - 1
# Previous Year corresponding start and end dates
py_start_date = min(start_date.day, calendar.monthrange(py_start_year, py_start_month)[1])
py_end_date = min(end_date.day, calendar.monthrange(py_end_year, py_end_month)[1])
# Sales current year
py_total_sales = sales[(sales['date'] >= py_start_date) &
(sales['date'] <= py_end_date)]['sales'].sum()
return [
html.P(py_start_date),
html.P(py_end_date)
]
if __name__ == '__main__':
app.run_server(debug=True)
Data format
date sales
0 2022-04-12 117
1 2023-05-17 102
2 2022-03-31 108
3 2023-05-10 130
4 2023-10-07 144
β¦ β¦ β¦
148 2022-12-02 117
149 2022-04-30 111
150 2023-10-11 119
151 2022-01-23 117
152 2023-09-10 140
what could be the problem? thanks in advance
start_date
and end_date
are strings. You need to convert them to a datetime object if you want to get the year, month, etc.
import datetime
start_date_str = '2024-09-23'
start_date_dt = datetime.datetime.strptime(start_date_str, '%Y-%m-%d')
print(start_date_dt.year)
Thanks PyGuy, This has worked.
The only challenge I have now is the dates are printed in this format. β2023-09-02T00:00:00β
thus below error
ValueError: unconverted data remains: T13:10:55.860229