def func(db, entry): start_at = entry['start_at'] if _end_at: end_at = timing.parse(start_at.strftime('%Y-%m-%d'), _end_at) else: end_at = datetime.now() if end_at.day == start_at.day: duration = timing.calc_duration(start_at, end_at) return db.execute('UPDATE entries SET end_at = ?, duration = ? WHERE id = ?', (end_at, duration, entry['id'])) else: prev_end_at = start_at.replace(hour=23, minute=59, second=00) duration = timing.calc_duration(start_at, prev_end_at) cursor = db.execute('UPDATE entries SET end_at = ?, duration = ? WHERE id = ?', (prev_end_at, duration, entry['id'])) create(entry['event'], '00:00', end_at.strftime('%H:%M'), end_at.strftime('%Y-%m-%d')) return cursor
def create(event, start_at, end_at, date_str=None): """ creates a new tracking entry and saves to database returns the id of newly created entry if success, otherwise None """ start_at = timing.parse(date_str, start_at) end_at = timing.parse(date_str, end_at) duration = timing.calc_duration(start_at, end_at) db = get_db() with db: cursor = db.execute( 'INSERT INTO entries (event, start_at, end_at, duration) VALUES (?, ?, ?, ?);', (event, start_at, end_at, duration) ) return cursor.lastrowid
def update(entry_id, event, start_at, end_at, date_str=None): """ updates an existing tracking entry in the database returns True if updated successfully """ entry_id = int(entry_id) start_at = timing.parse(date_str, start_at) end_at = timing.parse(date_str, end_at) duration = timing.calc_duration(start_at, end_at) db = get_db() with db: cursor = db.execute( 'UPDATE entries SET event = ?, start_at = ?, end_at = ?, duration = ? WHERE id = ?;', (event, start_at, end_at, duration, entry_id) ) return (cursor.rowcount > 0)