Python 将日期转换为月份和年份

Python 将日期转换为月份和年份,python,Python,从以下日期开始,如何使用python获取月份和年份 日期是 "2011-07-01 09:26:11" //This showud display as "This month" "2011-06-07 09:26:11" //This should display as June "2011-03-12 09:26:11" //This should display as March

从以下日期开始,如何使用python获取月份和年份

日期是

           "2011-07-01 09:26:11"   //This showud display  as "This month"
           "2011-06-07 09:26:11"   //This should display as June            
           "2011-03-12 09:26:11"   //This should display as March            
           "2010-07-25 09:26:11"   // Should display as last year
请告诉我如何使用python 2.4获取这些格式


当pandas dataframe中有一个日期变量[格式相同]时,如何执行此操作?

您可以使用datetime.strTime粘贴日期。 但对于像您这样的简单情况,我只会使用正则表达式

>>>> import re
>>>> re.match('^(\d+)-(\d+)', "2011-07-01 09:26:11").groups()
('2011', '07')
应该大致按照你的要求去做

from datetime import datetime
a = datetime.strptime('2011-07-01 09:26:11', '%Y-%m-%d %H:%M:%S')
if a.month == datetime.now().month:
    print 'This month'

根据python日期/时间转换的良好站点得出的其他结果:

“//应该显示为去年的样子”在Python中不是一条评论,你可以在那里查看和工作。我可以在这里给出答案,这并不难。但是,请先提供一些自己的努力。Python非常有用。如果他们没有帮助你,回来要求解决你的问题。我不认为这比
d=datetime.strtime(“2011-07-01 09:26:11),%Y-%m-%d%H:%m:%S”)更简单;(d.year,d.month)
。不用的时候为什么要使用re呢。
from datetime import datetime
a = datetime.strptime('2011-07-01 09:26:11', '%Y-%m-%d %H:%M:%S')
if a.month == datetime.now().month:
    print 'This month'