Tags: 2000-12-06-, convert, date, dec, format, formate, programming, python, string, stringdate, value

Convert Date to Short formate

On Programmer » Python

2,307 words with 2 Comments; publish: Thu, 27 Dec 2007 19:07:00 GMT; (20062.01, « »)

Hello,

there is string value 'Dec 06, 2000' I want to convert that string

date to SHORT FORMAT like '2000-12-06-. Please help me how do I do

that? I'm new in Jython.

Thanks,

aqmaiya

All Comments

Leave a comment...

  • 2 Comments
    • aqmaiya wrote:

      > there is string value 'Dec 06, 2000' I want to convert that string

      > date to SHORT FORMAT like '2000-12-06-. Please help me how do I do

      > that?

      you mean ISO format, right?

      the easiest way is probably to use the time.strptime module to parse the

      original string into a time tuple, and then use time.strftime to format

      the tuple as an ISO date:

      >>> s = "Dec 06, 2000"

      >>> t = time.strptime(s, "%b %d, %Y")

      >>> t

      (2000, 12, 6, 0, 0, 0, 2, 341, -1)

      >>> time.strftime("%Y-%m-%d", t)

      '2000-12-06'

      also see:

      http://docs.python.org/lib/module-time.html

      </F

      #1; Thu, 27 Dec 2007 19:08:00 GMT
    • On 8/06/2006 5:50 AM, aqmaiya wrote:

      > Hello,

      > there is string value 'Dec 06, 2000' I want to convert that string

      > date to SHORT FORMAT like '2000-12-06-. Please help me how do I do

      > that? I'm new in Jython.

      > Thanks,

      > aqmaiya

      Two ways (at least):

      (1) check out the strptime and strftime (p == parse, f == format)

      functions in the time module

      In general, the datetime module is much to be preferred for working with

      dates and times -- unless of course you need to mimic functions from the

      C time.h library -- however the datetime module won't be getting a

      strptime until version 2.5, which is still in alpha test.

      (2) As you are new to Python, you might like to try your skills with

      basic parts from the Python toolkit, like dictionaries and slicing, and

      write a function yourself, specialised to that particular format. Here

      are some hints:

      # example Dec 06, 2000

      # ruler 0123456789012

      mpart = data[0:3]

      # similarly: dpart, ypart

      month_dict = {'jan': 1, ...., 'dec': 12}

      month_num = month_dict[mpart.lower()] # will work with Dec, dec, DEC

      result = '%s-%02d-%s' % (ypart, month_num, dpart)

      How much validation you do is up to you :-)

      HTH,

      John

      #2; Thu, 27 Dec 2007 19:09:00 GMT