gpt4 book ai didi

python - 将月份从 str 更改为 int 进行计算

转载 作者:行者123 更新时间:2023-11-30 22:27:31 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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)

关于python - 将月份从 str 更改为 int 进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com