views:

126

answers:

3

I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following date : 01/01/2008, 02/01/2008 and 31/12/2008. The algorithm would return 0, 16.667, and 100 (1 month = 16.667%).

I tried to play with the datetime and timedelta classes of Python 2.5 and I am unable to achieve this. I thought I could use the number of ticks, but I am not even able to get that info from datetime.

Any idea how I could write this algorithm in Python? Otherwise, any other ideas or algorithms?

A: 

I don't know if I fully understand what you are trying to do, but you can just deal with times as number of seconds since the UNIX epoch and then just use plain old subtraction to get a range that you can scale to the size of your plot.

In processing, the map function will handle this case for you. http://processing.org/reference/map_.html I'm sure you can adapt this for your purpose

Ben Hughes
+1  A: 

It's fairly easy to convert a timedelta into a numeric value.

Select an epoch time. Calculate deltas for every value relative to the epoch. Convert the delta's into a numeric value. Then map the numeric values as you normally would.

Conversion is straight forward. Something like:

def f(delta):
   return delta.seconds + delta.days * 1440 * 60 + 
      (delta.microseconds / 1000000.0)
James Schek
+3  A: 

If you're dealing with dates, then you can use the method toordinal.

import datetime

jan1=datetime.datetime(2008,1,1)
dec31=datetime.datetime(2008,12,31)
feb1=datetime.datetime(2008,02,01)

dates=[jan1,dec31,feb1]
dates.sort()

datesord=[d.toordinal() for d in dates]
start,end=datesord[0],datesord[-1]

def datetofloat(date,start,end):
    """date,start,end are ordinal dates
    ie Jan 1 of the year 1 has ordinal 1
       Jan 1 of the year 2008 has ordinal 733042"""
    return (date-start)*1.0/(end-start)

print datetofloat(dates[0],start,end)
  0.0
print datetofloat(dates[1],start,end)
  0.0849315068493*
print datetofloat(dates[2],start,end)
  1.0

*16.67% is about two months of a year, so the proportion for Feb 1 is about half of that.

Alasdair