How to get a date after a month in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • parthpatel
    New Member
    • Apr 2007
    • 14

    #1

    How to get a date after a month in python

    Suppose i have a date as (2007 / 04 / 25)


    now i need a date exactly after a month i.e. (2007 / 05 / 25)

    Is there any function which can help it out
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by parthpatel
    Suppose i have a date as (2007 / 04 / 25)


    now i need a date exactly after a month i.e. (2007 / 05 / 25)

    Is there any function which can help it out
    Code:
    >>> import datetime
    >>> dt = '2007 / 04 / 25'
    >>> d = datetime.date(*[int(i) for i in dt.split(' / ')])
    >>> d1 = d.replace(month=d.month+1)
    >>> dt = d1.strftime('%Y / %m / %d')
    >>> dt
    '2007 / 05 / 25'
    >>>

    Comment

    • dshimer
      Recognized Expert New Member
      • Dec 2006
      • 136

      #3
      Code:
      (*[int(i) for i in dt.split(' / ')])
      I have see you use this syntax before, could you (or anyone who gets it explain it once, or tell me where I can get a decent explanation.

      I am refering to the idea of putting the for loop and assigning the return values all in a single statement.

      I see it work, but just don't get the mechanics of it.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by dshimer
        Code:
        (*[int(i) for i in dt.split(' / ')])
        I have see you use this syntax before, could you (or anyone who gets it explain it once, or tell me where I can get a decent explanation.

        I am refering to the idea of putting the for loop and assigning the return values all in a single statement.

        I see it work, but just don't get the mechanics of it.
        It wasn't easy for me to understand either. There are two components to explain. First is the list comprehension of the form '[expression for item in list if condition]'.
        Code:
        >>> [i for i in range(10)]
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        >>> [(i+12)/4.5 for i in range(10) if i == 6]
        [4.0]
        >>>
        The '*' preceding the list comprehension expands the list as though the list elements were passed to the function as arguments. I think of it as the '*' removes the list brackets. In the example, the equivalent code is:
        Code:
        dt = '2007 / 05 / 25'
        dtList = dt.split(' / ')
        d = datetime.date(int(dtList[0]), int(dtList[1]), int(dtList[2]))
        
        print d
        print repr(d)
        '''2007-05-25
        datetime.date(2007, 5, 25)
        >>>
        '''
        HTH :)

        Comment

        • dshimer
          Recognized Expert New Member
          • Dec 2006
          • 136

          #5
          WOW! Thanks, that is too cool.

          Comment

          Working...