简体   繁体   中英

Converting a list of dates to a proper date type format in python

I have a list of dates:

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

I want to convert these dates to a datetime format ie 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?

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)

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']

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM