Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
datetime in SQL query.
#1
Hi

I'm using the code below to import from an ODBC database. At the moment I'm hard-coding the dates, for example, I can't work out the syntax to replace the second date with datetime.today().strftime('%Y-%m-%d'). Could anyone offer a suggestion where I'm going wrong.

columns_to_select = ['STOCK_CODE, RECORD_CREATE_DATE, TRAN_NUMBER, COST_PRICE, QUANTITY, TYPE']

# Construct the query
sql_query = f"""
SELECT {', '.join(columns_to_select)}
FROM STOCK_TRAN
WHERE RECORD_CREATE_DATE >= '2023-01-31' AND RECORD_CREATE_DATE < '2025-09-17'
"""
# Execute the query
df = pd.read_sql_query(sql_query, conn)


Thanks
Reply
#2
I'd suggest taking a gander at Date and Time Value Manipulation. This site has been around for a while, but stands solidly. It shown examples of each time of conversion. Don't forget to import datetime.
Reply
#3
(Sep-17-2025, 10:06 AM)Larz60+ Wrote: I'd suggest taking a gander at Date and Time Value Manipulation. This site has been around for a while, but stands solidly. It shown examples of each time of conversion. Don't forget to import datetime.

Thanks, I've already looked at that, and I already use datetime successfully already, specifically I can't seem to get the syntax working within the SQL query.
Reply
#4
I've figured it out. I needed squiggly brackets

WHERE RECORD_CREATE_DATE >= '2023-01-31' AND RECORD_CREATE_DATE < '{datetime.today().strftime('%Y-%m-%d')}'
Larz60+ likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' findbikash 2 12,721 Sep-18-2019, 08:32 AM
Last Post: buran

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.