Python 将月份从str更改为int以进行计算

Python 将月份从str更改为int以进行计算,python,string,datetime,integer,Python,String,Datetime,Integer,我需要将月份从字符串值更改为整数值,以便执行计算。我正在使用datetime库,它可以提供当前日期,我需要将其与用户输入的日期进行比较,以整数形式查找月份之间的差异 import datetime current_month = datetime.date.today().strftime('%B') month_join = input('Please enter the month you joined') month_difference = current_month - month_

我需要将月份从字符串值更改为整数值,以便执行计算。我正在使用datetime库,它可以提供当前日期,我需要将其与用户输入的日期进行比较,以整数形式查找月份之间的差异

import datetime

current_month = datetime.date.today().strftime('%B')
month_join = input('Please enter the month you joined')
month_difference = current_month - month_join
如果可能的话,我想输入一个月。如果没有,我将只使用:

month_join = int(input('Please enter the month you joined')

datetime中的strTime方法可能会对您有所帮助。例如:

import datetime

current_month = datetime.date.today().strftime('%B')
month_join = datetime.datetime.strptime(input('Please enter the month you joined'), "%B")
month_difference = current_month.month - month_join.month
但是要注意这一点-如果用户在上一个日历年加入了怎么办?您的月差最终将为负值

您最好实际获取用户加入的完整月份和年份,将其转换为datetime对象,从datetime.today()中减去它以获得timedelta对象。然后从该timedelta对象获取月份计数


您也可以尽可能地利用datetime库,而不是试图重新发明轮子

此方法允许用户在第一次出错时多次输入正确答案。它还会检查以确保该数字是有效的月份。您还可以添加检查,查看用户是否需要包括年份。IE:if
current\u month-month\u join<0
询问他们当年的情况

import datetime

current_month = datetime.date.today().month
month_join = None
while month_join is None:
    month_join = raw_input('Please enter the month you joined:  ')
    if month_join == 'quit':
        exit(1)
    try:
        month_join = int(month_join)
        if month_join > 12 or month_join < 1 or not isinstance(month_join, int):
            print('Please enter a month value that is from 1 to 12')
            month_join = None
    except Exception as e:
        if isinstance(e, TypeError) or isinstance(e, ValueError):
            print('Please enter the month as an integer. IE. May = 5. If you want to close the program type "quit"')
            month_join = None
        else:
            raise e
month_difference = current_month - month_join
print month_difference
导入日期时间
当前月份=datetime.date.today().month
月加入=无
当月加入为无时:
月加入=原始输入('请输入你加入的月份:')
如果月份_join==‘退出’:
出口(1)
尝试:
月加入=整数(月加入)
如果月加入>12或月加入<1或不存在(月加入,int):
打印('请输入从1到12'的月份值)
月加入=无
例外情况除外,如e:
如果isinstance(e,TypeError)或isinstance(e,ValueError):
print('请以整数形式输入月份。例如,May=5。如果要关闭程序,请键入“quit”')
月加入=无
其他:
提高e
月份差异=当前月份-月份
打印月差

听起来你需要的是一本字典,它将月份的名称与其数值联系起来

import datetime

month_names = ["January",   "February", "March",    "April",
               "May",       "June",     "July",     "August",
               "September", "October",  "November", "December"]

months = {name : (index + 1) for index, name in enumerate(month_names)}

current_month    = datetime.date.today().strftime('%B')
month_joined     = input("Please enter the month you joined: ")
month_difference = abs(months[current_month] - months[month_joined])

print(month_difference)
您还可以通过使用
calendar
模块的
month\u name
列表属性来完成字典的创建

import datetime, calendar

months = {name : (index + 1) for index, name in enumerate(calendar.month_name[1:])}

current_month    = datetime.date.today().strftime('%B')
month_joined     = input("Please enter the month you joined: ")
month_difference = abs(months[current_month] - months[month_joined])

print(month_difference)
试试图书馆


这看起来是可行的,但是为什么不利用datetime库为您完成这项工作呢?非常感谢您的帮助。这非常有效,但我需要比较年份和月份。我原以为年份是一个整数,但当从datetime引入时,它是一个字符串,这意味着我无法将其与输入进行比较。我应该在代码中添加月份吗?如何将其更改为整数。datetime的当前年份为:datetime.date.today().strftime(“%Y”)@Jack,您应该可以将其转换为整数:
int(datetime.date.today().strftime(“%Y”))
对我来说没有名为“monthdelta”的模块
monthdelta
不是核心Python库的一部分-我只是建议它作为一种可以很好工作的东西。如果您想安装它,与任何软件包一样,您可以在终端窗口中运行
pip install monthdelta
import datetime
import monthdelta

current_month = datetime.date.today()
year = current_month.year
month_in = input('Please enter the month you joined')
month_dt = datetime.datetime.strptime(month_in, '%B').date()

# Construct new datetime object with current year
month_join = datetime.date(year=year, month=month_dt.month, day=1)

# Reduce year by one if the month occurs later
if month_join > current_month:
    month_join = datetime.date(year=year - 1, month=month_dt.month, day=1)

month_difference = monthdelta.monthmod(month_join, current_month)
print(month_difference[0].months)