3

From the following dates how to get months and year using python

dates are

           "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

Please let me know how to get these formats using python 2.4

When I have a date variable[with same format] in pandas dataframe, how to perform this ?

Rajeev
  • 44,985
  • 76
  • 186
  • 285
  • ` // Should display as last year` is not a comment in python – Jakob Bowyer Jul 02 '11 at 11:01
  • You can take a look at http://stackoverflow.com/questions/410221/natural-relative-days-in-python/5164027#5164027 and work from there. – Sebastian Paaske Tørholm Jul 02 '11 at 11:02
  • I could give an answer here, that's not to hard. But, please provide some own efforts first. Python's [datetime docs](http://docs.python.org/library/datetime.html) are quite helpful. If they don't help you, come back and ask for a solution to your particular problem. – Oben Sonne Jul 02 '11 at 11:03

4 Answers4

5
import time
import calendar

current = time.localtime()

dates = ["2011-07-01 09:26:11", "2011-06-07 09:26:11", "2011-03-12 09:26:11", "2010-07-25 09:26:11"]

for date in dates:
    print "%s" % date
    date = time.strptime(date, "%Y-%m-%d %H:%M:%S")

    if date.tm_year == current.tm_year - 1:
        print "Last year"    

    elif date.tm_mon == current.tm_mon:
        print "This month"

    else:
        print calendar.month_name[date.tm_mon]

Should do roughly what you ask for.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
3
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'

The other results according to http://docs.python.org/library/datetime.html

Bari
  • 31
  • 1
0

Good site for python date/time conversions: http://www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/

Jason Strimpel
  • 14,670
  • 21
  • 76
  • 106
-2

You could use datetime.strptime to paste the date. But for simple case like yours, i would just use regex.

>>>> import re
>>>> re.match('^(\d+)-(\d+)', "2011-07-01 09:26:11").groups()
('2011', '07')
Ryan Ye
  • 3,159
  • 1
  • 22
  • 26