Question

Here's something that seems a little silly: datetime.strptime() is happy to accept an iterated list of month names when I just create a list by hand (months = ['January','February']) but not when I iterate over a list of months created by calendar.month_name even though both return <type 'str'>

Broken code:

import datetime
import calendar
for month in calendar.month_name:
    print datetime.datetime.strptime(month,"%B")

Error: ValueError: time data '' does not match format '%B'

Working code:

import datetime
months = ['January','February','March']
for month in months:
    print datetime.datetime.strptime(month,"%B")

Result:

1900-01-01 00:00:00
1900-02-01 00:00:00
1900-03-01 00:00:00

What's going on here? Is this a behavior of python's for loop I am not familiar with?

Was it helpful?

Solution

Try doing print( list(calendar.month_name) ) and it will become obvious pretty quickly why this fails ... (mainly because the first element yielded is an empty string). Note that the reason the first month yielded is an empty string is because they want month_names[1] to correspond to January as is the common convention (see the documentation)

You could do something like this:

a = list( calendar.month_names )[1:]

or this also works in Cpython at least (although it isn't clear in the documentation if it should):

a = calendar.month_names[1:]

OTHER TIPS

As noted by mgilson the first item returned is an empty string. It's trivial to ignore it:

for month in calendar.month_name:
    if month:
        print datetime.datetime.strptime(month,"%B")

Or to use a list comprehension to remove it:

for month in [month_name for month_name in calendar.month_name if month_name]:
    print datetime.datetime.strptime(month,"%B")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top