我在运行代码时遇到了先前的追溯错误-尽管我以为我可以正确格式化所有内容。
这是回溯
File "/alien.py", line 267, in filter_ufo_by_year
return ufo_by_year(filter_sightings(filter_text))
File "/alien.py", line 96, in ufo_by_year
in groupby('shape', sightings).items()
File "/alien.py", line 95, in <dictcomp>
for shape, class_sightings
File "lib/python3.6/site-packages/toolz/recipes.py", line 24, in
countby
return frequencies(map(key, seq))
File "lib/python3.6/site-packages/toolz/itertoolz.py", line 539, in
frequencies
for item in seq:
File "/alien.py", line 32, in sighting_year
return dt.datetime.strptime(sighting['date_time'],
TIMESTAMP_FORMAT).year
File
"/python/3.6.5/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File
"/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '' does not match format '%Y-%m-%dT%H:%M:%S'
以下是相关代码:
TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
def sighting_year(sighting):
return dt.datetime.strptime(sighting['date_time'],
TIMESTAMP_FORMAT).year
def ufo_by_year(sightings):
sightings_by_year = {
shape:
sorted(
list(
# Group by year -> count.
countby(sighting_year, class_sightings).items()
),
# Sort by year.
key=first
)
for shape, class_sightings
in groupby('shape', sightings).items()
}
# Build the plot with a dictionary.
return {
"data": [
{
"type": "scatter",
"mode": "lines+markers",
"name": shape,
"x": listpluck(0, class_sightings_by_year),
"y": listpluck(1, class_sightings_by_year)
}
for shape, class_sightings_by_year
in sightings_by_year.items()
],
"layout": {
"title": "Sightings by Year",
"showlegend": False
}
}
以下是“ date_time”的示例单元格:2015-07-25T21:45:00
在这里提供任何帮助
答案 0 :(得分:0)
您提供的字符串中没有时区:
>>> sample_datetime = "2015-07-25T21:45:00"
>>> obj = dt.datetime.strptime(sample_datetime, TIMESTAMP_FORMAT)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mm92400/anaconda3/envs/py36/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/Users/mm92400/anaconda3/envs/py36/lib/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '2015-07-25T21:45:00' does not match format '%Y-%m-%dT%H:%M:%SZ'
从格式字符串中删除Z
obj = dt.datetime.strptime(sample_datetime, '%Y-%m-%dT%H:%M:%S')
>>> obj
datetime.datetime(2015, 7, 25, 21, 45)