Skip to content

Instantly share code, notes, and snippets.

@salticus
Created February 16, 2017 06:56
Show Gist options
  • Select an option

  • Save salticus/50d5f45d2221e043f2992a6ecd2f252c to your computer and use it in GitHub Desktop.

Select an option

Save salticus/50d5f45d2221e043f2992a6ecd2f252c to your computer and use it in GitHub Desktop.
Destructive hack to delete all transactions in a GNUCash file except those in the target year.
#!/usr/bin/env python
"""
Create gnucash file with transactions only in the target year.
Delete all others.
Requires a gnucash file in sqlite3 format.
To convert an XML GNUCash file to SQLite3,
"Save As -> Select sqlite3 as the format"
If on Ubuntu the only "Save As" option is XML, try
`sudo apt install libdbd-sqlite3`
Then restart GNUCash and try again.
"""
import datetime
import piecash
import pytz
TZ_MT = pytz.timezone("US/Mountain")
CURRENCY = "USD"
def delete_transactions(gnucash_sql_filename, not_in_year):
"""Delete all transactions not_in_year from gnucash_sql_filename"""
start = datetime.datetime(not_in_year, 1, 1, 0, 0, 0, 0, TZ_MT)
finish = datetime.datetime(not_in_year, 12, 31, 23, 59, 59, 99, TZ_MT)
book = piecash.open_book(gnucash_sql_filename, readonly=False)
transactions = [x for x in book.transactions if not start <= x.post_date <= finish]
# piecash uses SQLAlchemy to interact with GNUCash sqlite3 files; hence the
# `session.delete`. It may be possible to fire off a `DELETE FROM transactions WHERE`
# but one would want to check piecash's ORM mappings for any required side effects
# before trying that.
session = book.session
for t in transactions:
session.delete(t)
session.commit()
book.close()
delete_transactions("original-2015-2017-sql.gnucash", 2016)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment