convert time

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Sep 11 07:00:55 CEST 2011


守株待兔 wrote:

> how can i convert "Dec 11" into  2011-12?


if my_str == "Dec 11":
    return 1999  # 2011 - 12


Does that help?

But seriously... 2011-12 is not a proper date, so the simplest way is
probably something like this:

def convert(date_str):
    month, short_year = date_str.split()
    if len(short_year) == 4:
        year = short_year
    else:
        year = '20' + short_year
    months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
    month = months.index(month) + 1
    return year + '-' + str(month)

Otherwise see the time and datetime modules:

http://docs.python.org/library/time.html
http://docs.python.org/library/datetime.html


-- 
Steven




More information about the Python-list mailing list