Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

dictionary - Datetime formatter of python works for one string and does not for another

I have a dictionary whose keys needs to be converted to a datetime object and format it to an understandable format. This is the dictionary

blah =  {
            "COLUMNNAME": "Some thing",
            "RID": 6,
            "Y202009": 15791.68,
            "Y202006": 8149.99,
            "Y202003": 27252.75,
            "Y201912": 19885.85,
            "Y201909": 18748.21,
            "rowno": 5.0
        } 

And this is the function to convert the keys into desired format

def dict_process(idict):
    del idict["RID"]
    del idict['rowno']
    for key, val in idict.items():
        try:
            new_key = str(datetime.strptime(key,"Y%Y%m").strftime("%Y %b"))
            idict[new_key] = idict.pop(key)
        except:
            None
    return None

But this function returns a dictionary which is like this

{'COLUMNNAME': 'Net Sales',
 'Y201912': 19885.85,
 'Y201909': 18748.21,
 '2020 Sep': 15791.68,
 '2020 Jun': 8149.99,
 '2020 Mar': 27252.75}

Could anyone help me with why the formatter is not working for years that contain 2019?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...