Skip to content

Instantly share code, notes, and snippets.

@Rufflewind
Created January 1, 2016 07:38
Show Gist options
  • Save Rufflewind/50290d55769321c807ae to your computer and use it in GitHub Desktop.
Save Rufflewind/50290d55769321c807ae to your computer and use it in GitHub Desktop.
TIMEUNIT_MICROSECOND = 0
TIMEUNIT_SECOND = 1
TIMEUNIT_MINUTE = 2
TIMEUNIT_HOUR = 3
TIMEUNIT_DAY = 4
TIMEUNIT_MONTH = 5
TIMEUNIT_YEAR = 6
def round_datetime(timeunit):
'''Round the given time downward to some unit of time. For example:
'round_datetime(TIMEUNIT_YEAR)(2015-12-12)' will yield 2015-01-01.'''
def inner(t):
if timeunit > TIMEUNIT_MICROSECOND:
t = t.replace(microsecond=0)
if timeunit > TIMEUNIT_SECOND:
t = t.replace(second=0)
if timeunit > TIMEUNIT_MINUTE:
t = t.replace(minute=0)
if timeunit > TIMEUNIT_HOUR:
t = t.replace(hour=0)
if timeunit > TIMEUNIT_DAY:
t = t.replace(day=1)
if timeunit > TIMEUNIT_MONTH:
t = t.replace(month=1)
return t
return inner
def bin_events(events, rounder):
'''Read a sequence of temporal events and bin them according to the
rounding function provided by 'rounder'.
The 'events' argument should a list of pairs '(time, weight)'. If each
event is counted equally, then weight should be just 1.
The 'rounder' argument must a function that rounds the time to some
discrete scale.
'''
bins = {}
for time, weight in events:
binned_time = rounder(time)
if binned_time not in bins:
bins[binned_time] = 0
bins[binned_time] += weight
return sorted(bins.items(), key=(lambda x: x[0]))
def transpose(lists):
return zip(*lists)
import csv, datetime
import matplotlib.pyplot as plt
with open("downloads/chat.csv", "rt") as f:
reader = csv.reader(f)
next(reader)
fmt = "%Y-%m-%dT%H:%M:%S"
events = [(datetime.datetime.strptime(r[3], fmt), 1) for r in reader]
xs, ys = transpose(bin_events(events, round_datetime(TIMEUNIT_DAY)))
plt.fill_between(xs, 0, ys, color="#9b19e6", linewidth=.2)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment