1

I have a list of dates:

dates = ["Jan2016","Feb2016","Mar2016"]

I want to convert these dates to a datetime format i.e Jan2016 = 201601

My first thought was to create a dict of months and their associated numbers and then map that over the list.

months = {"Jan":1,"Feb":2,"Mar":3}

Here is my current code:

dates = ["Jan2016","Feb2016","Mar2016"]
dic   = {"Jan":1, "Feb":2,"Mar":3}

month = []
year  = []

for date in dates:
    month.append(date[:3])
    year.append(date[3:])


month = [dic[n] if n in dic else n for n in month]

d = dict(zip(month,year))

print(d)

The output of this code is a dict like so:

{1: '2016', 2: '2016', 3: '2016'}

What is the most pythonic solution to this problem?

3
  • 3
    A datetime implies that there is a day and a time too. You only have a month and year. Commented Jan 20, 2017 at 15:18
  • Why a dictionary? What should happen with ['Jan2015', 'Jan2016']? Commented Jan 20, 2017 at 15:19
  • This is true. For this example the day and time is inconsequential as long as the months are formatted correctly. Commented Jan 20, 2017 at 15:20

3 Answers 3

2

As @Martijin commented, you can not have a datetime as 201601, but if you want a string instead, you can use strptime and strftime from datetime module to convert:

dates = ["Jan2016","Feb2016","Mar2016"]

from datetime import datetime

[datetime.strftime(datetime.strptime(d, "%b%Y"), "%Y%m") for d in dates]

# ['201601', '201602', '201603']

In case you are not familiar with conversion specification, %b stands for month abbreviation names, %Y Year with century, %m Month as decimal number(0-12)

Sign up to request clarification or add additional context in comments.

1 Comment

You should remove import datetime since it is unused.
1

hello you can try with a map()

months = {"Jan":"01", "Feb":"02", "Mar":"03"}
dates = ["Jan2016","Feb2016","Mar2016"]
list = map(lambda x :x[3:] + months[x[:3]], dates)

ouput:

['201601', '201602', '201603']

Comments

0

You can use the following:

from datetime import datetime

datetime.strptime('Jan2016', '%b%Y')

For your list, you can combine the above with a list comprehension:

>>> res = [datetime.strptime(d, '%b%Y') for d in dates]
>>> [datetime.strftime(d, "%Y%m") for d in res]
['201601', '201602', '201603']

Note: Since the day is missing in your dates list, 1 would be used for day (for res items).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.