sql - 如何按日期键对字典进行排序
问题描述
如何根据月份和年份对日期进行排序?
sorted()
将仅按月订购。
result = cur.execute("""SELECT order_delivered_customer_date
FROM orders
WHERE order_status == 'delivered'
ORDER BY orders.order_delivered_customer_date ASC""")
# iterate through the query result
#store the month and count of days in month for transaction in dictDates
for row in result:
datetp = parser.parse(row[0]) #convert the string to date type
parsedDate = datetp.strftime('%m-%Y') #format to month and year
if parsedDate in dictDates:
existingVal = dictDates[parsedDate]
updateVal = existingVal + 1
dictDates[parsedDate] = updateVal
else:
dictDates[parsedDate] = 1
print(dictDates)
##输出 {'12-2017': 23801, '01-2017': 7569, '01-2018': 24498, '11-2018': 8983, '06-2018': 27654, '07-2018': 24082,“03-2018”:29526,“10-2018”:9315,“05-2017”:17254,“08-2018”:31551,“11-2017”:23509,“05-2018”:27297, '12-2018': 7009, '04-2018': 28024, '09-2018': 10455, '10-2017': 18852, '02-2017': 8977, '07-2017': 16889, '09 -2017': 17492, '04-2017': 10982, '08-2017': 17791, '03-2017': 13630, '02-2018': 26582, '06-2017': 15661, '10-2016 ':771,'06-2016':93,'04-2016':33,'07-2016':78,'05-2016':11,'08-2016':39,'09-2016': 24,“11-2016”:111,“12-2016”:20,“01-2016”:32,“03-2016”:20}
解决方案
根据 dbms 这应该可以工作:
result = cur.execute("""SELECT order_delivered_customer_date
FROM orders
WHERE order_status == 'delivered'
ORDER BY year(orders.order_delivered_customer_date), month(orders.order_delivered_customer_date) ASC""")
推荐阅读
- pandas - 有趣的熊猫 groupby 困惑
- jakarta-ee - CDI 事件和 EJB 观察者的安全上下文
- python - 按每个主题的唯一值移动日期
- r - 多个动态选项卡创建中的条件面板
- python - 使用 databricks-connect 的 Azure 数据块连接
- python - matplotlib 中所有子图的相同 x-ticks
- amazon-web-services - 如何使用 Systems Manager `运行命令`
- reactjs - React.js,如何使用带有 setState 回调的 map 和 async 函数?
- python - 我不断收到无效的语法
- c - 如何比较两个结构成员的两个字符串的长度?