ValueError and datetime not making sense

Screen Link:

My Code:

import datetime as dt
result_list = []

for row in ask_posts:
    created_at = row[6]
    num_comments = int(row[4])
result_list.append([created_at, num_comments])

counts_by_hour = {}
comments_by_hour = {}
date_format = "%B %d, %Y %H:%M"

for row in result_list:
    hour = row[0]
    hour = dt.datetime.strptime(hour, date_format).time()
    date = dt.datetime.strptime(hour, date_format).date()
    time = hour.strftime("%H")
    comment = row[1]
    if hour not in counts_by_hour:
        counts_by_hour[time] = 1
        comment = counts_by_hour[time]
        comment = counts_by_hour[time] + 1


What I expected to happen:
For it to strip the time and start to count…

What actually happened:

ValueErrorTraceback (most recent call last)
<ipython-input-7-81353d9f33a7> in <module>()
      5 for row in result_list:
      6     hour = row[0]
----> 7     hour = dt.datetime.strptime(hour, date_format).time()
      8     date = dt.datetime.strptime(hour, date_format).date()
      9     time = hour.strftime("%H")

/usr/lib/python3.4/ in _strptime_datetime(cls, data_string, format)
    498     """Return a class cls instance based on the input string and the
    499     format string."""
--> 500     tt, fraction = _strptime(data_string, format)
    501     tzname, gmtoff = tt[-2:]
    502     args = tt[:6] + (fraction,)

/usr/lib/python3.4/ in _strptime(data_string, format)
    335     if not found:
    336         raise ValueError("time data %r does not match format %r" %
--> 337                          (data_string, format))
    338     if len(data_string) != found.end():
    339         raise ValueError("unconverted data remains: %s" %

ValueError: time data '5/21/2016 9:22' does not match format '%B %d, %Y %H:%M'

At this point it’s not making sense to set it up as I thought I was doing it correctly and now I’m confused and lost…

1 Like

Hello @liz.tracy09,

The error message ValueError: time data '5/21/2016 9:22' does not match format '%B %d, %Y %H:%M'.

This means that the value in your date_format variable does not match with the time data in your hour variable.
The time data in your hour variable is 5/21/2016 9:22 and as such, the value in your date_format variable should be: "%m/%d/%Y %H:%M".

I hope this helps.

1 Like

Hence, the correct code will be:

result_list = []
for post in ask_posts:
comments_by_hour = {}
counts_by_hour = {}

for row in result_list:
    hour = dt.datetime.strptime(row[0], "%m/%d/%Y %H:%M").strftime("%H")
    if hour in comments_by_hour:
        comments_by_hour[hour] += row[1]
        counts_by_hour[hour] += 1
        comments_by_hour[hour] = row[1]
        counts_by_hour[hour] = 1

I hope this helps.
1 Like

@liz.tracy09, is your code working properly now? If so, would you mind marking the answer as the solution?

1 Like

Thank you, that was super helpful and made sense!

1 Like

I am glad I could be of help.

Good luck and Happy learning!