繁体   English   中英

检查python字典中键的值

[英]Check the value of a key in a python dictionary

所以,我有这本字典:

days_per_month = {"01": 31, "02": 28,
                "03": 31, "04": 30,
                "05": 31, "06": 30,
                "07": 31, "08": 31,
                "09": 30, "10": 31,
                "11": 30, "12": 31}

而这个功能:

def add_months(month):
"""
If needed, increment one day and check other parameters, such as months and years.

Requires:
- dmy str with a date represented as DD:MM:YY.
Ensures: str with the updated date represented as DD:MM:YY.
"""
if month == 2:
    day = get_days(dmy)
    if check_year(year) == "True":
        if day > 29:
            month += 1
            day = 1
    else:
        if day > 28:
            month += 1
            day = 1
if days_per_month[month] = 31:
    day = get_days(dmy)
    if day > 31:
        month += 1
        day = 1
if days_per_month[month] = 30:
    day = get_days(dmy)
    if day > 30:
        month += 1
        day = 1
return month

函数get_days:

def get_days(dmy):
"""Get the number of days from a DD:MM:YY date representation.

Requires: dmy str with a date represented as DD:MM:YY.
Ensures: int with the number of days
"""
return int(dmy.split(':')[0])

函数check_year:

def check_year(year):
"""
Checks if the current year is a leap year or not.

Requires: year str with the year.
Ensures: 'True' if year is leap year; 'False' if year isn't a leap year.
"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

这是我要做的事情:我有一个以前的功能,我将x分钟增加到一定的时间,我们称它为y。 假设y =“ 23:56”,x =“ 5”,23:56 + 5 = 24:01。 因此,我还有另一种功能,它会在发生这种情况的日期增加一天。 现在,我正在尝试完成更改“月”的功能。 例如:y = 23:56,x = 5,== 24:01。 但是以前的日期是31/12,现在是32/12:我使用以前的函数增加了一天的时间,但是现在我还必须使用函数add_months更改月份。 因此,我检查了days_per_month词典并尝试查找月份(词典中的键)的值,以便获得该月的最大天数。 我认为这就是我应该做的方式,但是我不断收到此错误:

if days_per_month[month] = 31:

SyntaxError:语法无效

if days_per_month[month] = 30:

SyntaxError:语法无效

我究竟做错了什么?

Obs1-Python 3.2 Obs2-如果您有任何改善我任何功能的建议,请告诉我!

您的基本问题是您尝试分配一个值而不是对其进行比较。 使用if days_per_month[month] == 31:代替if days_per_month[month] = 31:

但是我建议使用这样的日期时间:

from datetime import *
a=datetime(2017,2,28,23,56,00)
b=a+timedelta(minutes=5)

我要做的是使用日期28.02.2017 23:56:00初始化a ,然后向该日期时间添加5分钟,并在b获得日期01.03.2017 00:01:00

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM