convert time

S

Steven D'Aprano

守株待兔 said:
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
 
N

nn

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.htmlhttp://docs.python.org/library/datetime.html

Just a small comment that you can get "months" by doing:

from calendar import month_abbr
months = list(month_abbr)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,414
Latest member
GayleWedel

Latest Threads

Top