Python-使用日期时间将日期字符串从YYYY-MM-DD转换为DD-MMM-YYYY? [英] Python - convert date string from YYYY-MM-DD to DD-MMM-YYYY using datetime?

查看:295
本文介绍了Python-使用日期时间将日期字符串从YYYY-MM-DD转换为DD-MMM-YYYY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经阅读了很多有关该主题的文章,但仍然感到困惑.任何帮助将由衷的感谢.

So I have read a number of threads on this, and am still stumped. Any help would be sincerely appreciated.

我在数据框中有一个包含日期字符串的列,或者什么都不包含.字符串采用以下格式:2017-10-17,即YYYY-MM-DD.

I have a column in a dataframe that contains strings of dates, or nothing. Strings are in this format: 2017-10-17, i.e. YYYY-MM-DD.

我想将它们转换为DD-MMM-YYYY,因此上面的内容为17-Oct-2017.

I want to convert these to DD-MMM-YYYY, so the above would read 17-Oct-2017.

这是我所拥有的代码,似乎什么也没做.它不会出错,但实际上不会修改日期.他们和以前一样.我一开始就这样称呼它:import datetime

Here is the code that I have, which seems to do nothing. It doesn't error out, but it doesn't actually modify the dates; they are the same as before. I'm calling this in the beginning: import datetime

df_combined['VisitDate'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%d-%b-%Y') if x != "" else "")

我希望它返回的字符串格式不同于从列中读取原始字符串时的格式.

I expected this to return a string in a different format than the format the original string was in when it's read from the column.

推荐答案

您可能只需要将结果分配回列本身即可:

You probably just need to assign the result back to the column itself:

df_combined['VisitDate'] = df_combined['VisitDate'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%d-%b-%Y') if x != "" else "")

这篇关于Python-使用日期时间将日期字符串从YYYY-MM-DD转换为DD-MMM-YYYY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆