我有一个像这样结构化的SQLite数据库:
ID Date Time Cost
"1" "2016-05-14" "17:39:35.925973" "1.98"
"2" "2016-05-14" "17:39:54.181083" "2.84"
"3" "2016-05-14" "17:40:26.408492" "2.99"
"4" "2016-05-14" "17:41:28.197353" "3.39"
"25" "2016-05-19" "14:44:27.235790" "2.5"
"26" "2016-05-19" "14:46:35.177696" "1.58"
"27" "2016-05-19" "14:49:12.902651" "0.1"
"28" "2016-05-20" "21:35:32.446997" "2.25"
我想在一个月和一年中总结成本,无视当天。
我在python中这样做,但我甚至不知道sqlite代码只选择月份和年份。
我试过这段代码:
def SumByMonth():
usrDate = raw_input('Enter yymm: ')
dateyear = datetime.datetime.strptime(usrDate, "%y%m").date()
month_sql = '''SELECT cost FROM Finance WHERE strftime('%m%y', date) = ( ? )'''
month_price = [t[0] for t in cur.execute(month_sql, ( dateyear,) )]
sum_total = sum(month_price)
print 'sum is for', dateyear,'is', sum_total
所有我回来的都是sum is for 2016-05-01 is 0
所以它似乎是在没有提供一天的情况下选择该月的第一天。我怎样才能选择月份和年份?
由于
答案 0 :(得分:1)
SQLite没有2位数年份的格式说明符。参考:https://www.sqlite.org/lang_datefunc.html
而且,正如@DanielRoseman所提到的那样:
取而代之的是:
def SumByMonth():
yyyymm = raw_input('Enter yyyymm: ')
month_sql = '''SELECT cost FROM Finance WHERE strftime('%Y%m',date) = ?'''
month_price = [t[0] for t in cur.execute(month_sql,(yyyymm,))]
sum_total = sum(month_price)
print 'sum is for', yyyymm,'is', sum_total
你可以做得更精彩:
def SumByMonth():
yyyymm = raw_input('Enter yyyymm: ')
month_sql = '''SELECT SUM(cost) FROM Finance WHERE strftime('%Y%m',date) = ?'''
sum_total = cur.execute(month_sql,(yyyymm,)).fetchone()[0]
print 'sum is for', yyyymm,'is', sum_total