簡體   English   中英

將數字從str更改為int進行計算

[英]Changing months from str to int for calculation

我需要將月份從字符串值更改為整數值,以便我可以執行計算。 我正在使用可以提供當前日期的日期時間庫,我需要將其與用戶輸入的日期進行比較,以找出整數形式的月份之間的差異。

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中的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對象獲取月份計數。

您也可以盡可能地利用日期時間庫,而不是嘗試重新發明輪子。

如果第一次搞砸了,這種方法允許用戶多次輸入正確的答案。 它還會檢查以確保該號碼是有效的月份。 您還可以添加檢查以查看用戶是否需要包含年份。 IE:if 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

聽起來你需要的是一個字典,它涉及一個月的名稱及其數值。

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)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM