I have a list of UTC datetimes from my table. I want to get the distinct dates in a local timezone, and get the count of entries for each date- again, for the local timezone.
I'm sure I'm overcomplicating this problem, but I'm pretty new to Python & SQLAlchemy, let alone dates & times & timezones.
I am storing my timestamps in UTC using a column with default=utcnow()... this works great: 2019-07-05 06:19:59.920630
I can even display timestamps in the browser's current timezone as necessary (in other parts of the app).
However I am trying to run an SQLAlchemy query based on the timezone to just get the entries for that user's local day.
2019-07-05 06:19:59.920630 can be converted using my utc_to_local helper function into 2019-07-04 23:19:59.920630... so I need my query to include that datetime entry in my query for all records on "July 4, 2019"
So I was running an SQLAlchemy query to get a list of distinct dates
>>>uniquedays=db.session.query(func.distinct(func.DATE(TableClass.timestamp))).all()
but I just realized this is returning a list of dates that potentially don't have any records for the user's locale ... in my example, July 5th doesn't have any entries for my timezone- but it's being returned as a uniqueday.
So I can also return the datetimelist like so:
>>>datetimelist = db.session.query(TableClass.timestamp).all()
But now I've just got this list of datetime (I assume) tuples:
>>>datetime
[(datetime.datetime(2019, 6, 30, 21, 8, 11, 354018),), (datetime.datetime(2019, 6, 30, 21, 21, 58, 158467),), (datetime.datetime(2019, 6, 30, 23, 39, 8, 310248),)....................
I was using this to convert utc datetime into my local time:
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
I am using SQLite for now, but intend to switch to a MySQL database for production.