#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # # 8.1 Parsing Unix timestamps # It's not obvious how to deal with Unix timestamps in pandas -- it took me quite a while to figure this out. The file we're using here is a popularity-contest file I found on my system at `/var/log/popularity-contest`. # # Here's an [explanation of how this file works](http://popcon.ubuntu.com/README). # # I'm going to hope that nothing in it is sensitive :) # In[13]: # Read it, and remove the last row popcon = pd.read_csv('../data/popularity-contest', sep=' ', )[:-1] popcon.columns = ['atime', 'ctime', 'package-name', 'mru-program', 'tag'] # The colums are the access time, created time, package name, recently used program, and a tag # In[14]: popcon[:5] # The magical part about parsing timestamps in pandas is that numpy datetimes are already stored as Unix timestamps. So all we need to do is tell pandas that these integers are actually datetimes -- it doesn't need to do any conversion at all. # # We need to convert these to ints to start: # In[15]: popcon['atime'] = popcon['atime'].astype(int) popcon['ctime'] = popcon['ctime'].astype(int) # Every numpy array and pandas series has a dtype -- this is usually `int64`, `float64`, or `object`. Some of the time types available are `datetime64[s]`, `datetime64[ms]`, and `datetime64[us]`. There are also `timedelta` types, similarly. # # We can use the `pd.to_datetime` function to convert our integer timestamps into datetimes. This is a constant-time operation -- we're not actually changing any of the data, just how pandas thinks about it. # In[16]: popcon['atime'] = pd.to_datetime(popcon['atime'], unit='s') popcon['ctime'] = pd.to_datetime(popcon['ctime'], unit='s') # If we look at the dtype now, it's ` '1970-01-01'] # Now we can use pandas' magical string abilities to just look at rows where the package name doesn't contain 'lib'. # In[20]: nonlibraries = popcon[~popcon['package-name'].str.contains('lib')] # In[21]: nonlibraries.sort_values('ctime', ascending=False)[:10] # Okay, cool, it says that I I installed ddd recently. And postgresql! I remember installing those things. Neat. # The whole message here is that if you have a timestamp in seconds or milliseconds or nanoseconds, then you can just "cast" it to a `'datetime64[the-right-thing]'` and pandas/numpy will take care of the rest. #