nellie
nellie

Reputation: 23

Transform month abbreviation strings to date in python

I have a list with abbreviated month names

shortmonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

And I want to make each element as a date format in year 2020, so each element will be in the form of

'2020-01-01'

As a date and not a simple string. I am very new to python, if anyone could explain me how to do this.

Upvotes: 1

Views: 915

Answers (2)

Jiří Baum
Jiří Baum

Reputation: 6940

If you want to use datetime.datetime or datetime.date objects, and assuming you want all the months in order, you can skip the month abbreviation strings and do something like:

month_starts = [
    datetime.date(year=2020, month=month, day=1)
    for month in range(1, 13)
]

or

month_starts = [
    datetime.datetime(year=2020, month=month, day=1)
    for month in range(1, 13)
]

If you do need to work with the month abbreviation strings, you can do something like:

month_abbr = 'Apr'  # coming from a file, input or from elsewhere in the program

month_number = shortmonth.index(month_abbr) + 1
the_month_start = datetime.date(year=2020, month=month_number, day=1)

Upvotes: 2

BrokenBenchmark
BrokenBenchmark

Reputation: 19253

You can use range() to generate the month numbers; the shortmonth list is not necessary. You can do the following:

print(['2020-{0:02d}-01'.format(i) for i in range(1, 13)])

If you want to create datetime objects, you can do the following:

from datetime import datetime
print([datetime.strptime('2020-{0:02d}-01'.format(i), "%Y-%m-%d") for i in range(1, 13)])

Upvotes: 1

Related Questions