analyzing time

Skip Montanaro skip at pobox.com
Fri Jul 5 21:43:56 CEST 2013


> I have a table with a column of type date, with dates and time combined (like '1/6/2013 3:52:69PM'), that spans many months.  How would I pull out records that are the first and last entries per day?

You mentioned "table" and "column", which leads me to think you are
dealing with data in a SQL database.  If so, that would likely change
the problem solution significantly.

If you have something like lists of string data in Python though, you
might want to make sure your timestamps are in a normalized form
first, so you can accurately sort by the timestamps.  For that, my
weapon of choice is the dateutil package, and in particular, the
dateutil.parser module:

>>> x = dateutil.parser.parse("1/6/2013 3:52:59PM")
>>> x
datetime.datetime(2013, 1, 6, 15, 52, 59)
>>> print x
2013-01-06 15:52:59

Once your timestamps are represented as Python datetime objects, the
problem gets a bit easier, especially if you want to find the
beginning and ending timestamps of a bunch of dates.  Sort, then throw
some itertools.groupby pixie dust at it. My ancient, reptilian brain
has never quite grokked all that iterator stuff, so I won't hazard a
guess how to spell the exact solution.

Skip



More information about the Python-list mailing list