【问题标题】:Changing months from str to int for calculation将月份从 str 更改为 int 以进行计算
【发布时间】:2017-10-23 20:11:44
【问题描述】:

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

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')

【问题讨论】:

    标签: python string datetime integer


    【解决方案1】:

    听起来您需要的是一本将月份名称及其数值关联起来的字典。

    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_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.date.today().strftime("%Y")
    • @Jack,您应该可以将其转换为整数:int(datetime.date.today().strftime("%Y"))
    【解决方案2】:

    可能 datetime 中的 strptime 方法对你有一些用处。例如:

    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
    

    但请注意这一点 - 如果用户在上一个日历年加入会怎样?您最终会得到month_difference 的负值。

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

    您不妨尽可能多地利用日期时间库,而不是试图重新发明轮子。

    【讨论】:

      【解决方案3】:

      如果用户第一次搞砸了,此方法允许用户多次输入正确答案。它还会检查以确保该数字是有效月份。您还可以添加检查以查看用户是否需要包含年份。 IE:如果current_month - month_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
      

      【讨论】:

        【解决方案4】:

        试试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)
        

        【讨论】:

        • 我没有名为“monthdelta”的模块
        • monthdelta 不是核心 Python 库的一部分——我只是建议它作为一个很好用的东西。如果你想安装它,对于任何包,你可以在终端窗口中运行pip install monthdelta
        猜你喜欢
        • 2014-08-20
        • 2020-12-17
        • 2020-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 2021-04-15
        • 1970-01-01
        相关资源
        最近更新 更多