month name to month number and vice versa in python

后端 未结 12 1150
情书的邮戳
情书的邮戳 2020-11-29 20:13

I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a commo

相关标签:
12条回答
  • 2020-11-29 20:31
    form month name to number
    d=['JAN','FEB','MAR','April','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
    N=input()
    for i in range(len(d)):
        if d[i] == N:
            month=(i+1)
    print(month)
    
    0 讨论(0)
  • 2020-11-29 20:35

    One more:

    def month_converter(month):
        months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        return months.index(month) + 1
    
    0 讨论(0)
  • 2020-11-29 20:40

    To get the full calendar name from the month number, you can use calendar.month_name. Please see the documentation for more details: https://docs.python.org/2/library/calendar.html

    month_no = 1
    month = calendar.month_name[month_no]
    
    # month provides "January":
    print(month)
    
    
    
    0 讨论(0)
  • 2020-11-29 20:43

    Create a reverse dictionary using the calendar module (which, like any module, you will need to import):

    {month: index for index, month in enumerate(calendar.month_abbr) if month}
    

    In Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do

    dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)
    
    0 讨论(0)
  • 2020-11-29 20:49

    Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:

    from time import strptime
    monthWord = 'september'
    
    newWord = monthWord [0].upper() + monthWord [1:3].lower() 
    # converted to "Sep"
    
    print(strptime(newWord,'%b').tm_mon) 
    # "Sep" converted to "9" by strptime
    
    0 讨论(0)
  • 2020-11-29 20:52

    You can use below as an alternative.

    1. Month to month number:

    from time import strptime

    strptime('Feb','%b').tm_mon

    1. Month number to month:

    import calendar

    calendar.month_abbr[2] or calendar.month[2]

    0 讨论(0)
提交回复
热议问题