这个问题可以看作是Python and MSSQL: Filtering techniques while retrieving data from SQL的后续行动
基本上,我想从SQL Server检索动态设置的日期范围内的数据。
到目前为止,我已经能够成功运行以下代码。
import pyodbc
import pandas as pd
cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER=server IP address;DATABASE=dbname;UID=userid;PWD=psswd')
query_pf = "select * from PowerFactor where DeviceTimeStamp between '2019-03-07' and '2019-03-07' "
df_pf = pd.read_sql_query(query_pf,cnxn)
我希望将两个日期设置为动态。像today 00:00:45
和today -1 23:59:59
如何完成?也许我需要以param
格式传递dict
?
答案 0 :(得分:0)
DATEADD(小时,2,'2017/08/25')
根据需要使用getdate()作为当前日期 选择DATEADD(hour,2,'2017/08/25')
query_pf = "select * from PowerFactor where DeviceTimeStamp between
Convert(datetime,'2006-12-30 00:38:54',120) and Convert(datetime,'2006-12-30 00:38:54',120)
我认为这对您来说是最灵活的解决方案,您可以传递所需的日期时间。由于无法运行传递旧日期功能,因此getdate不够有效。因此请以正确的格式Convert(datetime,' 2006-12-30 00:38:54',120)。
DATE & TIME FORMATS
0 select convert(varchar, getdate(), 0) Dec 12 2006 12:38AM
9 select convert(varchar, getdate(), 9) Dec 30 2006 12:38:54:840AM
13 select convert(varchar, getdate(), 13) 30 Dec 2006 00:38:54:840AM
20 select convert(varchar, getdate(), 20) 2006-12-30 00:38:54
21 select convert(varchar, getdate(), 21) 2006-12-30 00:38:54.840
22 select convert(varchar, getdate(), 22) 12/30/06 12:38:54 AM
25 select convert(varchar, getdate(), 25) 2006-12-30 00:38:54.840
100 select convert(varchar, getdate(), 100) Dec 30 2006 12:38AM
109 select convert(varchar, getdate(), 109) Dec 30 2006 12:38:54:840AM
113 select convert(varchar, getdate(), 113) 30 Dec 2006 00:38:54:840
120 select convert(varchar, getdate(), 120) 2006-12-30 00:38:54
121 select convert(varchar, getdate(), 121) 2006-12-30 00:38:54.840
126 select convert(varchar, getdate(), 126) 2006-12-30T00:38:54.840
127 select convert(varchar, getdate(), 127) 2006-12-30T00:38:54.840