(no subject)

Mike Rovner mike at bindkey.com
Thu Jun 5 21:36:09 CEST 2003


Message"Leeds, Mark" <mleeds at mlp.com> wrote in message
news:C497480353EF904FBF7A8B0851E5422C9F7F3A at MAIL002.AD.MLP.COM...
>i have a date, say as a string 26Nov2002 and i want to convert it to a
string >20021126.
Your problem that your don't have a date ;)
You have a string and nobody except you knows that is a date.
There modules (time in the standard library and others) that have their own
notion about date represented as string and AFAIK none of them is same as
yours.

>it's probably possible to write a function to do this by creating
>a table of months to numbers but I was hoping that
>there was some kind of python function i could use instead ?

So custom function may be best suited for you in that situation.

def num_date(str_date):
  assert len(str_date)==9, 'Date format shall be DDMONYYYY'
  assert type(str_date)==type(''), 'Date shall be a string'
  d,m,y=str_date[:2], str_date[2:5], str_date[5:]

month=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','De
c']
  try: n=month.index(m)
  except ValueError: raise ValueError, "Can't convert month "+m
  return '%s%02d%s' % (y,n,d)

Only you know how much test you need for input data:
- can day be 1 digit,
- do you have to check date and year ranges
and so on.

OTOH, if you need variety of input data then you might go for say time
module, but you have to convert your data then and/or dial with platform
restriction (say time.strptime() function for parsing string is available on
unix only).

Regards,
Mike








More information about the Python-list mailing list