from datetime import datetime as dt SEP = "\",\"" LS = "\"" LE = "\"" NL = LS + "\n" + LE def flat_dict_to_csv(data): keys = set() for i in data: keys = keys.union(set(i.keys())) keys = sorted(keys) out = SEP.join(keys) for i in data: out += NL + SEP.join([escape(i.get(j, "")) for j in keys]) return LS + out + LE def escape(value): val = str(value) val = val.replace(".", ",") return val def pretty_ts(timestamp, fmt="%Y-%m-%d %H:%M:%S"): d = dt.fromtimestamp(int(timestamp)/1000.0) return d.strftime(fmt)