简体   繁体   English

如何在Python中将“开始日期”和“结束日期”作为命令行参数传递

[英]How can I pass “start date” and “end date” as command line arguments in Python

I am trying to transfer data from one table to another using Python based on date range. 我正在尝试根据日期范围使用Python将数据从一个表转移到另一个表。

import anprint
import os
import sys
import re
import datetime
from mydb import cursor

try:
    cam_name = sys.argv[1]
    rec_date = sys.argv[2]
except:
    print "Usage: %s cam_name date " % sys.argv[0]
    sys.exit(1)

dbObj = anprint.ExcelDb()

# Get a list of the plates...
tablename = "customer_1.%s_anpr_vega" % cam_name
sql = """SELECT plate, datetime, id FROM %s WHERE DATE(datetime)="%s" """ % (tablename, rec_date)
cursor.execute(sql)
retval = cursor.fetchall()
for values in retval:
    print values
    (vrm, vrm_datetime, record_id) = values
    dbObj.reconcile_plate(cam_name, vrm, vrm_datetime, record_id)

1) It bad paractice: 1)不好的做法:

sql = """SELECT plate, datetime, id FROM %s WHERE DATE(datetime)="%s" """ % (tablename, rec_date)
cursor.execute(sql)

Do below: 请执行以下操作:

sql = """SELECT plate, datetime, id FROM %s WHERE DATE(datetime)=?""" % tablename
cursor.execute(sql, [rec_date])

2) It's simple and not good solution to use sys.argv[n] for get command line arguments like cam_name = sys.argv[1] . 2)使用sys.argv[n]来获取命令行参数(例如cam_name = sys.argv[1] )是简单而不是好的解决方案。 Good way is to use argparse for assign command line arguments to script. 好的方法是使用argparse为脚本分配命令行参数。

3) It's good practice use between operator in sql like this: 3)最好在sql中的运算符between使用between例如:

sql = "SELECT plate, datetime, id FROM " +tablename+ " WHERE datetime between ? and ?"
    cursor.execute(sql, [start_date, end_date])

Furthermore read it for understanding parameters style SQL query. 进一步阅读它以了解参数样式的SQL查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以将命令行参数传递给Abaqus python吗? - Can I pass command-line arguments to Abaqus python? 我如何在新行上显示 pandas 中 start_date 和 end_date 之间每个月的天数? - how can i have on a new line the number of days for each month between start_date and end_date in pandas? 如何在Python中将日期传递给脚本? - How can I pass a date to a script in Python? 如何使用 Python 中的常规条目将日期系列转换为开始和结束日期 - How to Convert the series of date to start and end date with regular entries in Python 如何以 Python 中的日期时间格式将结束日期设为比开始日期早 11 个月? - How do I take end date as 11 months ahead of start date in the datetime format in Python? 如何在Python中处理命令行参数? - How can I process command line arguments in Python? 如何指定某些命令行参数在 Python 中是必需的? - How can I specify that some command line arguments are mandatory in Python? 如何使用 vanila python 在命令行上获取 arguments? - How can I get the arguments on a command-line with vanila python? 如何将开始日期和结束日期之间的所有工作日加载到数据框? - How can I load all week days, between a start date and an end date, to a Data Frame? 如何检查结束日期是否不早于开始日期 django - How do I check if the end date is not before the start date django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM