Search code examples
pythonpython-3.xpython-datetime

ValueError: time data does not match


So I got this error raised

ValueError: time data '8/16/2016 9:55' does not match format '%m/&d/%Y %H:%M'.

I know that %m is the format for month with two digits (zero-padded). And as we can see that '8' (August) does not have zero padded. Is that the problem for this error? And how I fix this?

import datetime as dt
result_list = []
for a in ask_posts:
    result_list.append([a[6], int(a[4])])
counts_by_hour = {}
comments_by_hour = {}
date_format = '%m/&d/%Y %H:%M'

for row in result_list:
    date = row[0]
    comment = row[1]
    time = dt.datetime.strptime(date, date_format).strftime("%H")
    ``` I want  to extract the Hour only```
    if time not in counts_by_hour:
        counts_by_hour[time] = 1
        comments_by_hour[time] = comment
    else:
        counts_by_hour[time] += 1
        comments_by_hours[time] += comment

Solution

  • you have an error in your dateformat % not &

    import datetime as dt
    result_list = []
    for a in ask_posts:
        result_list.append([a[6], int(a[4])])
    counts_by_hour = {}
    comments_by_hour = {}
    date_format = '%m/%d/%Y %H:%M' #  change & with %
    
        for row in result_list:
            date = row[0]
            comment = row[1]
            time = dt.datetime.strptime(date, date_format).strftime("%H")
            ``` I want  to extract the Hour only```
            if time not in counts_by_hour:
                counts_by_hour[time] = 1
                comments_by_hour[time] = comment
            else:
                counts_by_hour[time] += 1
                comments_by_hours[time] += comment