检查python字典中键的值

2024-04-19 07:50:21 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有一本字典:

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

功能获取天数:

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

功能检查年份:

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\u months函数更改月份。所以,我检查我的days\u per\u month字典,并试图找到月份(字典中的键)的值,这样就可以得到该月份的最大天数。我想我应该这样做,但我不断地犯这个错误:

if days_per_month[month] = 31:

语法错误:无效语法

if days_per_month[month] = 30:

语法错误:无效语法

我做错什么了?你知道吗

Obs1-python 3.2版 如果您有任何建议,以改善我的任何功能,请告诉我!你知道吗


Tags: the函数dateifaswithdaysyear
1条回答
网友
1楼 · 发布于 2024-04-19 07:50:21

你的基本问题是,你试图分配一个值,而不是比较它。使用 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

相关问题 更多 >