1

I know it is possible to extract a month from a datetime in sqlalchemy as an integer with:

func.extract('month', datetime)

but is it possible to change the days of the datetime to 1 in that month in a Postgres database in order to plot the data in a graph like with:

func.strftime(datetime, '%Y-%m')

which doesn't work for Postgres databases?

I have tried:

func.to_char

but I need to get the datetime or at least the date grouped by month or week in order to plot the data over time in graphs and this doesn't seem to get a datetime unless I am doing something wrong. Any ideas?

I know that it is changing a datetime to a string, but for some reason the func.strftime worked for plotting the graphs with SQLite but func.char doesn't for Postgres.

Would I have to just create 3 seperate columns for week, month and year and then combine them into a datetime in order to plot a graph of data that I need grouped by weeks or months?

DidSquids
  • 149
  • 1
  • 8

2 Answers2

1

There are several approaches for this, depending on which database you're using. I've included a solution for postgres and mysql to demonstrate:

Postgres:

# Can be used to truncate a datetime value according to any interval
func.date_trunc('month', date_col)

MySql:

# This reformats to the nearest month
# you can manually format to the first day of the month
func.date_format(date_col, '%Y-%m-01')
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
0

I have seperated the week, month and year into seperate columns and queried the data. I ended up doing the calculations outside of sqlalchemy with the query result as I couldn't work it out inside the query. I have used this example to help me reach an answer - Get date from week number

I set the day to "1" represented as %w in the format for the data I got from the sqlalchemy query that grouped by week and year

datetime_by_week = [datetime.strptime(f'{int(i.year)}-{int(i.week)}-1', '%Y-%W-%w').date() for i in data]

For the month I got the month number and year number after grouping by month and year in the sqlalchemy query.

datetime_by_month = [datetime.strptime(f'{int(i.year)}-{int(i.month)}-01', '%Y-%m-%d').date() for i in data]
DidSquids
  • 149
  • 1
  • 8