如何将月份名称映射到月份编号,反之亦然?

发布于 2024-09-13 06:00:51 字数 316 浏览 8 评论 0原文

我正在尝试创建一个函数,可以将月份数字转换为缩写月份名称或将缩写月份名称转换为月份数字。我认为这可能是一个常见问题,但我在网上找不到。

我正在考虑 calendar 模块。我发现要将月份数字转换为缩写月份名称,您只需执行 calendar.month_abbr[num] 即可。但我看不出有什么办法可以朝另一个方向走。创建一个字典来转换另一个方向是处理这个问题的最佳方法吗?或者是否有更好的方法从月份名称到月份编号,反之亦然?

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 common question but I could not find it online.

I was thinking about the calendar module. I see that to convert from month number to abbreviated month name you can just do calendar.month_abbr[num]. I do not see a way to go in the other direction though. Would creating a dictionary for converting the other direction be the best way to handle this? Or is there a better way to go from month name to month number and vice versa?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

唐婉 2024-09-20 06:00:51

使用 calendar 模块创建反向字典(与任何模块一样,您需要导入该字典):

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

在 2.7 之前的 Python 版本中,由于该语言不支持字典理解语法,您将需要要做

dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)

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)
药祭#氼 2024-09-20 06:00:51

只是为了好玩:

from time import strptime

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

Just for fun:

from time import strptime

strptime('Feb','%b').tm_mon
俏︾媚 2024-09-20 06:00:51

使用 日历 模块:

Number-to-Abbr
calendar.month_abbr[month_number]

缩写到数字
列表(calendar.month_abbr).index(month_abbr)

Using calendar module:

Number-to-Abbr
calendar.month_abbr[month_number]

Abbr-to-Number
list(calendar.month_abbr).index(month_abbr)

薄凉少年不暖心 2024-09-20 06:00:51

这是另一种方法。

def monthToNum(shortMonth):
    return {
            'jan': 1,
            'feb': 2,
            'mar': 3,
            'apr': 4,
            'may': 5,
            'jun': 6,
            'jul': 7,
            'aug': 8,
            'sep': 9, 
            'oct': 10,
            'nov': 11,
            'dec': 12
    }[shortMonth]

Here's yet another way to do it.

def monthToNum(shortMonth):
    return {
            'jan': 1,
            'feb': 2,
            'mar': 3,
            'apr': 4,
            'may': 5,
            'jun': 6,
            'jul': 7,
            'aug': 8,
            'sep': 9, 
            'oct': 10,
            'nov': 11,
            'dec': 12
    }[shortMonth]
故事还在继续 2024-09-20 06:00:51

信息来源:Python Docs

从月份获取月份数字名称使用日期时间模块

import datetime
month_number = datetime.datetime.strptime(month_name, '%b').month

# To  get month name
In [2]: datetime.datetime.strftime(datetime.datetime.now(), '%a %b %d, %Y')
Out [2]: 'Thu Aug 10, 2017'

# To get just the month name, %b gives abbrevated form, %B gives full month name
# %b => Jan
# %B => January
dateteime.datetime.strftime(datetime_object, '%b')

Information source: Python Docs

To get month number from month name use datetime module

import datetime
month_number = datetime.datetime.strptime(month_name, '%b').month

# To  get month name
In [2]: datetime.datetime.strftime(datetime.datetime.now(), '%a %b %d, %Y')
Out [2]: 'Thu Aug 10, 2017'

# To get just the month name, %b gives abbrevated form, %B gives full month name
# %b => Jan
# %B => January
dateteime.datetime.strftime(datetime_object, '%b')
月棠 2024-09-20 06:00:51

这是一个更全面的方法,也可以接受完整的月份名称

def month_string_to_number(string):
    m = {
        'jan': 1,
        'feb': 2,
        'mar': 3,
        'apr':4,
         'may':5,
         'jun':6,
         'jul':7,
         'aug':8,
         'sep':9,
         'oct':10,
         'nov':11,
         'dec':12
        }
    s = string.strip()[:3].lower()

    try:
        out = m[s]
        return out
    except:
        raise ValueError('Not a month')

示例:

>>> month_string_to_number("October")
10 
>>> month_string_to_number("oct")
10

Here is a more comprehensive method that can also accept full month names

def month_string_to_number(string):
    m = {
        'jan': 1,
        'feb': 2,
        'mar': 3,
        'apr':4,
         'may':5,
         'jun':6,
         'jul':7,
         'aug':8,
         'sep':9,
         'oct':10,
         'nov':11,
         'dec':12
        }
    s = string.strip()[:3].lower()

    try:
        out = m[s]
        return out
    except:
        raise ValueError('Not a month')

example:

>>> month_string_to_number("October")
10 
>>> month_string_to_number("oct")
10
从﹋此江山别 2024-09-20 06:00:51

完整月份名称到月份编号(例如一月二月等):

import datetime

month_name = 'January'
month_num = datetime.datetime.strptime(month_name, '%B').month

print(month_num, type(month_num))

>> 1 <class 'int'>

部分月份名称到月份编号(例如< em>一月、二月等..):

import datetime

month_name = 'Feb'
month_num = datetime.datetime.strptime(month_name, '%b').month

print(month_num, type(month_num))

>> 2 <class 'int'>

您还可以将其格式化为两位数表示形式:

month_num = 3
formatted = f"{month_num:02}"

print(formatted, type(formatted))

>> 03 <class 'str'>

月份数字到完整的月份名称(可以是双位数)数字表示与否,字符串或整数)(例如 '01'1 等):

import datetime

month_num = '04'  # month_num = 4 will work too
month_name = datetime.datetime(1, int(month_num), 1).strftime("%B")

print(month_name)

>> April

月份数字到部分月份名称(无论是否为两位数,字符串或整数)(例如 '01'1 等):

import datetime

month_num = 5  # month_num = '05' will work too
month_name = datetime.datetime(1, int(month_num), 1).strftime("%b")

print(month_name)

>> May

Full month name to month number (e.g. January, February, etc..):

import datetime

month_name = 'January'
month_num = datetime.datetime.strptime(month_name, '%B').month

print(month_num, type(month_num))

>> 1 <class 'int'>

Partial month name to month number (e.g. Jan, Feb, etc..):

import datetime

month_name = 'Feb'
month_num = datetime.datetime.strptime(month_name, '%b').month

print(month_num, type(month_num))

>> 2 <class 'int'>

You can also format it to double-digits representation:

month_num = 3
formatted = f"{month_num:02}"

print(formatted, type(formatted))

>> 03 <class 'str'>

Month number to full month name (either double-digits representation or not, either string or int) (e.g. '01', 1, etc..):

import datetime

month_num = '04'  # month_num = 4 will work too
month_name = datetime.datetime(1, int(month_num), 1).strftime("%B")

print(month_name)

>> April

Month number to partial month name (either double-digits representation or not, either string or int) (e.g. '01', 1, etc..):

import datetime

month_num = 5  # month_num = '05' will work too
month_name = datetime.datetime(1, int(month_num), 1).strftime("%b")

print(month_name)

>> May
故事灯 2024-09-20 06:00:51

再来一张:

def month_converter(month):
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    return months.index(month) + 1

One more:

def month_converter(month):
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    return months.index(month) + 1
愚人国度 2024-09-20 06:00:51

要从月份编号获取完整的日历名称,您可以使用calendar.month_name。请参阅文档了解更多详细信息: https://docs.python.org/2/库/calendar.html

month_no = 1
month = calendar.month_name[month_no]

# month provides "January":
print(month)


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)


濫情▎り 2024-09-20 06:00:51

将月份名称转换为列表时,可以使用 index 方法。月份名称的索引将对应于月份的数字:

list(calendar.month_abbr).index('Jan')  # returns 1

这是calendar.month_abbr[1]的逆操作。

When converting the month names to a list, you can use the index method. The index of the month name will correspond to the number of the month:

list(calendar.month_abbr).index('Jan')  # returns 1

This is the reverse operation of calendar.month_abbr[1].

一个人的夜不怕黑 2024-09-20 06:00:51

使用日期时间

datetime.strptime("Jan", "%b").month

使用时间

time.strptime("Jan", "%b").tm_mon

Using datetime:

datetime.strptime("Jan", "%b").month

Using time:

time.strptime("Jan", "%b").tm_mon
勿忘初心 2024-09-20 06:00:51
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)
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)
轻许诺言 2024-09-20 06:00:51

你可以尝试:

pd.to_datetime(df['month'], format='%b').dt.month

You could try with:

pd.to_datetime(df['month'], format='%b').dt.month
装纯掩盖桑 2024-09-20 06:00:51

基于上述想法,这对于将月份名称更改为适当的月份编号非常有效:

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

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
萌梦深 2024-09-20 06:00:51

您可以使用下面作为替代方案。

  1. 月份编号:

from time import strptime

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

  1. 月份编号:

导入日历

calendar.month_abbr[2]
日历.月份[2]

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]

一紙繁鸢 2024-09-20 06:00:51
def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))
def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))
只是在用心讲痛 2024-09-20 06:00:51

如果您不想导入日历库,并且需要更强大的东西 - 您可以使您的代码比其他一些解决方案对不一致的文本输入更加动态假如。您可以:

  1. 通过该字典的 .items()创建一个 month_to_number 字典
  2. 循环,并检查字符串 s 的小写字母是否在小写键k

month_to_number = {
'January' : 1,         
'February' : 2,         
'March' : 3,           
'April' : 4,              
'May' : 5, 
'June' : 6,
'July' : 7, 
'August' : 8, 
'September' : 9, 
'October' : 10, 
'November' : 11, 
'December' : 12}

s = 'jun'
[v for k, v in month_to_number.items() if s.lower() in k.lower()][0]

Out[1]: 6

同样,如果您有一个列表 l 而不是字符串,则可以添加另一个 for 来循环列表。我创建的列表具有不一致的值,但输出仍然是正确月份数字所需的:

l = ['January', 'february', 'mar', 'Apr', 'MAY', 'JUne', 'july']
[v for k, v in month_to_number.items() for m in l if m.lower() in k.lower()]

Out[2]: [1, 2, 3, 4, 5, 6, 7]

我这里的用例是我使用 Selenium 从网站中抓取数据根据某些条件自动选择下拉值。不管怎样,这需要我依赖一些我相信我们的供应商每月手动输入标题的数据,如果他们的格式与历史上的格式略有不同,我不想回到我的代码。

If you don't want to import the calendar library, and need something that is a bit more robust -- you can make your code a little bit more dynamic to inconsistent text input than some of the other solutions provided. You can:

  1. Create a month_to_number dictionary
  2. loop through the .items() of that dictionary and check if the lowercase of a string s is in a lowercase key k.

month_to_number = {
'January' : 1,         
'February' : 2,         
'March' : 3,           
'April' : 4,              
'May' : 5, 
'June' : 6,
'July' : 7, 
'August' : 8, 
'September' : 9, 
'October' : 10, 
'November' : 11, 
'December' : 12}

s = 'jun'
[v for k, v in month_to_number.items() if s.lower() in k.lower()][0]

Out[1]: 6

Likewise, if you have a list l instead of a string, you can add another for to loop through the list. The list I have created has inconsistent values, but the output is still what would be desired for the correct month number:

l = ['January', 'february', 'mar', 'Apr', 'MAY', 'JUne', 'july']
[v for k, v in month_to_number.items() for m in l if m.lower() in k.lower()]

Out[2]: [1, 2, 3, 4, 5, 6, 7]

The use case for me here is that I am using Selenium to scrape data from a website by automatically selecting a dropdown value based off of some conditions. Anyway, this requires me relying on some data that I believe our vendor is manually entering to title each month, and I don't want to come back to my code if they format something slightly differently than they have done historically.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文