将数字从str更改为int进行计算

时间:2017-10-23 20:11:44

标签: python string datetime integer

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

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

4 个答案:

答案 0 :(得分:1)

日期时间中的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.today()中删除它以获取timedelta对象。然后从该timedelta对象获取月份计数。

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

答案 1 :(得分:1)

此方法允许用户在第一次搞砸时有多次机会输入正确的答案。它还会检查以确保该号码是有效的月份。您还可以添加检查以查看用户是否需要包含年份。 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

答案 2 :(得分: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)

答案 3 :(得分:0)

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