日期时间转换不完整

时间:2018-10-29 13:46:16

标签: python python-3.x datetime datetime-format

我试图编写一个函数来从字典中获取星期,月份和星期几,这取决于城市的信息(纽约,芝加哥,华盛顿),我面临的问题是只有华盛顿市的日期显示和当我尝试显示其他城市时,它会一直显示华盛顿城市日期

功能如下:

from datetime import datetime

def time_of_trip(datum, city):

    for x in datum:

        if city == "NYC":
            timeformatted = datetime.strptime(str(datum[x]), "(%m, %H, '%A')")
        elif city == "Chicago":
            timeformatted = datetime.strptime(str(datum[x]), "(%m, %H, '%A')")
        elif city == "Washington":
            timeformatted = datetime.strptime(str(datum[x]), "(%m, %H, '%A')")


    month = datetime.strftime(timeformatted, "%m")
    hour = datetime.strftime(timeformatted, "%H")
    day_of_week = datetime.strftime(timeformatted, "%A")


    return (month, hour, day_of_week)


tests = {'NYC': (1, 0, 'Friday'),
         'Chicago': (3, 21, 'Thursday'),
         'Washington': (3, 22, 'Thursday')}


time_of_trip(tests, "NYC")

1 个答案:

答案 0 :(得分:1)

由于您已经知道您感兴趣的键(城市),因此没有必要遍历字典(除非您使用Python 3.7,否则字典将以任意顺序提供给您)。相反,您可以直接访问该密钥:

from datetime import datetime

def time_of_trip(datum, city):
    timeformatted = datetime.strptime(str(datum[city]), "(%m, %H, '%A')")
    month = datetime.strftime(timeformatted, "%m")
    hour = datetime.strftime(timeformatted, "%H")
    day_of_week = datetime.strftime(timeformatted, "%A")
    return (month, hour, day_of_week)


tests = {'NYC': (1, 0, 'Friday'),
         'Chicago': (3, 21, 'Thursday'),
         'Washington': (3, 22, 'Thursday')}

print(time_of_trip(tests, "NYC"))
# ('01', '00', 'Monday')
print(time_of_trip(tests, "Washington"))
# ('03', '22', 'Thursday')
print(time_of_trip(tests, "Chicago"))
# ('03', '21', 'Thursday')