Python Datetime problem: Is There a better solution












0















I found the correct solution to the following problem which uses python 3 datetime objects. However, my solution seems really messy and I was wondering if I could get some help to clean it up:



Question:
Complete the which_date() function below which returns the day that follows a specified time period after an initial date. Time periods can be specified in two different ways: as a number of days like "1 day" or "30 days", or as a number of weeks like "2 weeks" or "12 weeks".



def which_date(start_date,time):
"""
This function takes as input a string depicting a date in YYYY/mm/dd
format and a string stating a time period in the form of "X day(s)" or
"Y week(s)". Output should be a string in form YYYY/mm/dd with the date
that is X days or Y weeks after the initial date.
"""

# Every thing after this comment and before 'return end_date' is my
#code to solve this probmem
start_date_split = start_date.split('/')
start_date_split = list(map(int, start_date_split))
year, month, day = start_date_split[0], start_date_split[1],
start_date_split[2]
start_date_date_obj = datetime.date(year, month, day)

time_split = time.split(' ')
time_amount = int(time_split[0])
days_or_weeks = time_split[1]

time_to_add = datetime.timedelta(0)
if 'day' in days_or_weeks:
time_to_add = datetime.timedelta(days = time_amount)
else:
time_to_add = datetime.timedelta(weeks = time_amount)

end_date_date_obj = start_date_date_obj + time_to_add
end_date = end_date_date_obj.strftime('%Y/%m/%d')
return end_date


The following is the verification test:



def test():
assert which_date('2016/02/10','35 days') == '2016/03/16'
assert which_date('2016/12/21','3 weeks') == '2017/01/11'
assert which_date('2015/01/17','1 week') == '2015/01/24'
print("All tests completed.")









share|improve this question























  • Look at datetime format conversions; they should be able to cut out a few lines of ugly split/int/etc.

    – Prune
    Nov 15 '18 at 20:39











  • start_date_date_obj = datetime.datetime.strptime(start_date, '%Y/%m/%d') is the obvois thing i see (as mentioned by Prune).

    – hiro protagonist
    Nov 15 '18 at 20:41






  • 1





    This question might be appropriate for codereview.stackexchange.com

    – Adrian W
    Nov 15 '18 at 20:56
















0















I found the correct solution to the following problem which uses python 3 datetime objects. However, my solution seems really messy and I was wondering if I could get some help to clean it up:



Question:
Complete the which_date() function below which returns the day that follows a specified time period after an initial date. Time periods can be specified in two different ways: as a number of days like "1 day" or "30 days", or as a number of weeks like "2 weeks" or "12 weeks".



def which_date(start_date,time):
"""
This function takes as input a string depicting a date in YYYY/mm/dd
format and a string stating a time period in the form of "X day(s)" or
"Y week(s)". Output should be a string in form YYYY/mm/dd with the date
that is X days or Y weeks after the initial date.
"""

# Every thing after this comment and before 'return end_date' is my
#code to solve this probmem
start_date_split = start_date.split('/')
start_date_split = list(map(int, start_date_split))
year, month, day = start_date_split[0], start_date_split[1],
start_date_split[2]
start_date_date_obj = datetime.date(year, month, day)

time_split = time.split(' ')
time_amount = int(time_split[0])
days_or_weeks = time_split[1]

time_to_add = datetime.timedelta(0)
if 'day' in days_or_weeks:
time_to_add = datetime.timedelta(days = time_amount)
else:
time_to_add = datetime.timedelta(weeks = time_amount)

end_date_date_obj = start_date_date_obj + time_to_add
end_date = end_date_date_obj.strftime('%Y/%m/%d')
return end_date


The following is the verification test:



def test():
assert which_date('2016/02/10','35 days') == '2016/03/16'
assert which_date('2016/12/21','3 weeks') == '2017/01/11'
assert which_date('2015/01/17','1 week') == '2015/01/24'
print("All tests completed.")









share|improve this question























  • Look at datetime format conversions; they should be able to cut out a few lines of ugly split/int/etc.

    – Prune
    Nov 15 '18 at 20:39











  • start_date_date_obj = datetime.datetime.strptime(start_date, '%Y/%m/%d') is the obvois thing i see (as mentioned by Prune).

    – hiro protagonist
    Nov 15 '18 at 20:41






  • 1





    This question might be appropriate for codereview.stackexchange.com

    – Adrian W
    Nov 15 '18 at 20:56














0












0








0








I found the correct solution to the following problem which uses python 3 datetime objects. However, my solution seems really messy and I was wondering if I could get some help to clean it up:



Question:
Complete the which_date() function below which returns the day that follows a specified time period after an initial date. Time periods can be specified in two different ways: as a number of days like "1 day" or "30 days", or as a number of weeks like "2 weeks" or "12 weeks".



def which_date(start_date,time):
"""
This function takes as input a string depicting a date in YYYY/mm/dd
format and a string stating a time period in the form of "X day(s)" or
"Y week(s)". Output should be a string in form YYYY/mm/dd with the date
that is X days or Y weeks after the initial date.
"""

# Every thing after this comment and before 'return end_date' is my
#code to solve this probmem
start_date_split = start_date.split('/')
start_date_split = list(map(int, start_date_split))
year, month, day = start_date_split[0], start_date_split[1],
start_date_split[2]
start_date_date_obj = datetime.date(year, month, day)

time_split = time.split(' ')
time_amount = int(time_split[0])
days_or_weeks = time_split[1]

time_to_add = datetime.timedelta(0)
if 'day' in days_or_weeks:
time_to_add = datetime.timedelta(days = time_amount)
else:
time_to_add = datetime.timedelta(weeks = time_amount)

end_date_date_obj = start_date_date_obj + time_to_add
end_date = end_date_date_obj.strftime('%Y/%m/%d')
return end_date


The following is the verification test:



def test():
assert which_date('2016/02/10','35 days') == '2016/03/16'
assert which_date('2016/12/21','3 weeks') == '2017/01/11'
assert which_date('2015/01/17','1 week') == '2015/01/24'
print("All tests completed.")









share|improve this question














I found the correct solution to the following problem which uses python 3 datetime objects. However, my solution seems really messy and I was wondering if I could get some help to clean it up:



Question:
Complete the which_date() function below which returns the day that follows a specified time period after an initial date. Time periods can be specified in two different ways: as a number of days like "1 day" or "30 days", or as a number of weeks like "2 weeks" or "12 weeks".



def which_date(start_date,time):
"""
This function takes as input a string depicting a date in YYYY/mm/dd
format and a string stating a time period in the form of "X day(s)" or
"Y week(s)". Output should be a string in form YYYY/mm/dd with the date
that is X days or Y weeks after the initial date.
"""

# Every thing after this comment and before 'return end_date' is my
#code to solve this probmem
start_date_split = start_date.split('/')
start_date_split = list(map(int, start_date_split))
year, month, day = start_date_split[0], start_date_split[1],
start_date_split[2]
start_date_date_obj = datetime.date(year, month, day)

time_split = time.split(' ')
time_amount = int(time_split[0])
days_or_weeks = time_split[1]

time_to_add = datetime.timedelta(0)
if 'day' in days_or_weeks:
time_to_add = datetime.timedelta(days = time_amount)
else:
time_to_add = datetime.timedelta(weeks = time_amount)

end_date_date_obj = start_date_date_obj + time_to_add
end_date = end_date_date_obj.strftime('%Y/%m/%d')
return end_date


The following is the verification test:



def test():
assert which_date('2016/02/10','35 days') == '2016/03/16'
assert which_date('2016/12/21','3 weeks') == '2017/01/11'
assert which_date('2015/01/17','1 week') == '2015/01/24'
print("All tests completed.")






python function datetime






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 20:34









SharkShark

1




1













  • Look at datetime format conversions; they should be able to cut out a few lines of ugly split/int/etc.

    – Prune
    Nov 15 '18 at 20:39











  • start_date_date_obj = datetime.datetime.strptime(start_date, '%Y/%m/%d') is the obvois thing i see (as mentioned by Prune).

    – hiro protagonist
    Nov 15 '18 at 20:41






  • 1





    This question might be appropriate for codereview.stackexchange.com

    – Adrian W
    Nov 15 '18 at 20:56



















  • Look at datetime format conversions; they should be able to cut out a few lines of ugly split/int/etc.

    – Prune
    Nov 15 '18 at 20:39











  • start_date_date_obj = datetime.datetime.strptime(start_date, '%Y/%m/%d') is the obvois thing i see (as mentioned by Prune).

    – hiro protagonist
    Nov 15 '18 at 20:41






  • 1





    This question might be appropriate for codereview.stackexchange.com

    – Adrian W
    Nov 15 '18 at 20:56

















Look at datetime format conversions; they should be able to cut out a few lines of ugly split/int/etc.

– Prune
Nov 15 '18 at 20:39





Look at datetime format conversions; they should be able to cut out a few lines of ugly split/int/etc.

– Prune
Nov 15 '18 at 20:39













start_date_date_obj = datetime.datetime.strptime(start_date, '%Y/%m/%d') is the obvois thing i see (as mentioned by Prune).

– hiro protagonist
Nov 15 '18 at 20:41





start_date_date_obj = datetime.datetime.strptime(start_date, '%Y/%m/%d') is the obvois thing i see (as mentioned by Prune).

– hiro protagonist
Nov 15 '18 at 20:41




1




1





This question might be appropriate for codereview.stackexchange.com

– Adrian W
Nov 15 '18 at 20:56





This question might be appropriate for codereview.stackexchange.com

– Adrian W
Nov 15 '18 at 20:56












3 Answers
3






active

oldest

votes


















0














Did some list destructuring to cut down on some lines of code. Also removed the creation of some new variables and just used the values directly:



import datetime

def which_date(start_date,time):
"""
This function takes as input a string depicting a date in YYYY/mm/dd
format and a string stating a time period in the form of "X day(s)" or
"Y week(s)". Output should be a string in form YYYY/mm/dd with the date
that is X days or Y weeks after the initial date.
"""

# Every thing after this comment and before 'return end_date' is my
# code to solve this problem

year, month, day = [int(each) for each in start_date.split('/')]

start_date_date_obj = datetime.date(year, month, day)

time_amount, days_or_weeks = [int(value) if index==0 else value for index, value in enumerate(time.split(' '))]

time_to_add = datetime.timedelta(days = time_amount) if days_or_weeks=='days' else datetime.timedelta(weeks = time_amount)

return (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

def test():
assert which_date('2016/02/10','35 days') == '2016/03/16'
assert which_date('2016/12/21','3 weeks') == '2017/01/11'
assert which_date('2015/01/17','1 week') == '2015/01/24'
print("All tests completed.")

test()





share|improve this answer































    0














    You can use regular expressions in order to have a 'cleaner' function:



    import re
    import datetime


    def which_date(start_date, time):
    # Split your date into a list by using non-decimal characters as separators
    year, month, day = re.split(r'D', start_date)
    start_date_date_obj = datetime.date(int(year), int(month), int(day))

    # Create group captures in order to get the quantity of day(s)/week(s)
    # and pass those as generic arguments to timedelta
    time_match = re.search(r'(d+) (day|week)[s]?', time)
    args = {time_match.group(2) + 's': int(time_match.group(1))}
    time_to_add = datetime.timedelta(**args)

    end_date_date_obj = start_date_date_obj + time_to_add
    end_date = end_date_date_obj.strftime('%Y/%m/%d')
    return end_date





    share|improve this answer































      0














      Here's a more simple version of a previous answer. I'm a beginner so I can't understand all of the advanced code here.



      import datetime
      def which_date(start_date,time):
      """
      This function takes as input a string depicting a date in YYYY/mm/dd
      format and a string stating a time period in the form of "X day(s)" or
      "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
      that is X days or Y weeks after the initial date.
      """

      year, month, day = [int(each) for each in start_date.split('/')]


      start_date_date_obj = datetime.date(year, month, day)

      add = 1
      string = time.split()
      if string[1] == "days" or string[1] == "day":
      add = int(string[0])
      else:
      add = (int(string[0]))*7



      time_to_add = datetime.timedelta(days = add)

      end_date = (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

      return end_date





      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53327515%2fpython-datetime-problem-is-there-a-better-solution%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Did some list destructuring to cut down on some lines of code. Also removed the creation of some new variables and just used the values directly:



        import datetime

        def which_date(start_date,time):
        """
        This function takes as input a string depicting a date in YYYY/mm/dd
        format and a string stating a time period in the form of "X day(s)" or
        "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
        that is X days or Y weeks after the initial date.
        """

        # Every thing after this comment and before 'return end_date' is my
        # code to solve this problem

        year, month, day = [int(each) for each in start_date.split('/')]

        start_date_date_obj = datetime.date(year, month, day)

        time_amount, days_or_weeks = [int(value) if index==0 else value for index, value in enumerate(time.split(' '))]

        time_to_add = datetime.timedelta(days = time_amount) if days_or_weeks=='days' else datetime.timedelta(weeks = time_amount)

        return (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

        def test():
        assert which_date('2016/02/10','35 days') == '2016/03/16'
        assert which_date('2016/12/21','3 weeks') == '2017/01/11'
        assert which_date('2015/01/17','1 week') == '2015/01/24'
        print("All tests completed.")

        test()





        share|improve this answer




























          0














          Did some list destructuring to cut down on some lines of code. Also removed the creation of some new variables and just used the values directly:



          import datetime

          def which_date(start_date,time):
          """
          This function takes as input a string depicting a date in YYYY/mm/dd
          format and a string stating a time period in the form of "X day(s)" or
          "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
          that is X days or Y weeks after the initial date.
          """

          # Every thing after this comment and before 'return end_date' is my
          # code to solve this problem

          year, month, day = [int(each) for each in start_date.split('/')]

          start_date_date_obj = datetime.date(year, month, day)

          time_amount, days_or_weeks = [int(value) if index==0 else value for index, value in enumerate(time.split(' '))]

          time_to_add = datetime.timedelta(days = time_amount) if days_or_weeks=='days' else datetime.timedelta(weeks = time_amount)

          return (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

          def test():
          assert which_date('2016/02/10','35 days') == '2016/03/16'
          assert which_date('2016/12/21','3 weeks') == '2017/01/11'
          assert which_date('2015/01/17','1 week') == '2015/01/24'
          print("All tests completed.")

          test()





          share|improve this answer


























            0












            0








            0







            Did some list destructuring to cut down on some lines of code. Also removed the creation of some new variables and just used the values directly:



            import datetime

            def which_date(start_date,time):
            """
            This function takes as input a string depicting a date in YYYY/mm/dd
            format and a string stating a time period in the form of "X day(s)" or
            "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
            that is X days or Y weeks after the initial date.
            """

            # Every thing after this comment and before 'return end_date' is my
            # code to solve this problem

            year, month, day = [int(each) for each in start_date.split('/')]

            start_date_date_obj = datetime.date(year, month, day)

            time_amount, days_or_weeks = [int(value) if index==0 else value for index, value in enumerate(time.split(' '))]

            time_to_add = datetime.timedelta(days = time_amount) if days_or_weeks=='days' else datetime.timedelta(weeks = time_amount)

            return (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

            def test():
            assert which_date('2016/02/10','35 days') == '2016/03/16'
            assert which_date('2016/12/21','3 weeks') == '2017/01/11'
            assert which_date('2015/01/17','1 week') == '2015/01/24'
            print("All tests completed.")

            test()





            share|improve this answer













            Did some list destructuring to cut down on some lines of code. Also removed the creation of some new variables and just used the values directly:



            import datetime

            def which_date(start_date,time):
            """
            This function takes as input a string depicting a date in YYYY/mm/dd
            format and a string stating a time period in the form of "X day(s)" or
            "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
            that is X days or Y weeks after the initial date.
            """

            # Every thing after this comment and before 'return end_date' is my
            # code to solve this problem

            year, month, day = [int(each) for each in start_date.split('/')]

            start_date_date_obj = datetime.date(year, month, day)

            time_amount, days_or_weeks = [int(value) if index==0 else value for index, value in enumerate(time.split(' '))]

            time_to_add = datetime.timedelta(days = time_amount) if days_or_weeks=='days' else datetime.timedelta(weeks = time_amount)

            return (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

            def test():
            assert which_date('2016/02/10','35 days') == '2016/03/16'
            assert which_date('2016/12/21','3 weeks') == '2017/01/11'
            assert which_date('2015/01/17','1 week') == '2015/01/24'
            print("All tests completed.")

            test()






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 20:56









            natn2323natn2323

            651318




            651318

























                0














                You can use regular expressions in order to have a 'cleaner' function:



                import re
                import datetime


                def which_date(start_date, time):
                # Split your date into a list by using non-decimal characters as separators
                year, month, day = re.split(r'D', start_date)
                start_date_date_obj = datetime.date(int(year), int(month), int(day))

                # Create group captures in order to get the quantity of day(s)/week(s)
                # and pass those as generic arguments to timedelta
                time_match = re.search(r'(d+) (day|week)[s]?', time)
                args = {time_match.group(2) + 's': int(time_match.group(1))}
                time_to_add = datetime.timedelta(**args)

                end_date_date_obj = start_date_date_obj + time_to_add
                end_date = end_date_date_obj.strftime('%Y/%m/%d')
                return end_date





                share|improve this answer




























                  0














                  You can use regular expressions in order to have a 'cleaner' function:



                  import re
                  import datetime


                  def which_date(start_date, time):
                  # Split your date into a list by using non-decimal characters as separators
                  year, month, day = re.split(r'D', start_date)
                  start_date_date_obj = datetime.date(int(year), int(month), int(day))

                  # Create group captures in order to get the quantity of day(s)/week(s)
                  # and pass those as generic arguments to timedelta
                  time_match = re.search(r'(d+) (day|week)[s]?', time)
                  args = {time_match.group(2) + 's': int(time_match.group(1))}
                  time_to_add = datetime.timedelta(**args)

                  end_date_date_obj = start_date_date_obj + time_to_add
                  end_date = end_date_date_obj.strftime('%Y/%m/%d')
                  return end_date





                  share|improve this answer


























                    0












                    0








                    0







                    You can use regular expressions in order to have a 'cleaner' function:



                    import re
                    import datetime


                    def which_date(start_date, time):
                    # Split your date into a list by using non-decimal characters as separators
                    year, month, day = re.split(r'D', start_date)
                    start_date_date_obj = datetime.date(int(year), int(month), int(day))

                    # Create group captures in order to get the quantity of day(s)/week(s)
                    # and pass those as generic arguments to timedelta
                    time_match = re.search(r'(d+) (day|week)[s]?', time)
                    args = {time_match.group(2) + 's': int(time_match.group(1))}
                    time_to_add = datetime.timedelta(**args)

                    end_date_date_obj = start_date_date_obj + time_to_add
                    end_date = end_date_date_obj.strftime('%Y/%m/%d')
                    return end_date





                    share|improve this answer













                    You can use regular expressions in order to have a 'cleaner' function:



                    import re
                    import datetime


                    def which_date(start_date, time):
                    # Split your date into a list by using non-decimal characters as separators
                    year, month, day = re.split(r'D', start_date)
                    start_date_date_obj = datetime.date(int(year), int(month), int(day))

                    # Create group captures in order to get the quantity of day(s)/week(s)
                    # and pass those as generic arguments to timedelta
                    time_match = re.search(r'(d+) (day|week)[s]?', time)
                    args = {time_match.group(2) + 's': int(time_match.group(1))}
                    time_to_add = datetime.timedelta(**args)

                    end_date_date_obj = start_date_date_obj + time_to_add
                    end_date = end_date_date_obj.strftime('%Y/%m/%d')
                    return end_date






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 15 '18 at 21:12









                    Aurora WangAurora Wang

                    818418




                    818418























                        0














                        Here's a more simple version of a previous answer. I'm a beginner so I can't understand all of the advanced code here.



                        import datetime
                        def which_date(start_date,time):
                        """
                        This function takes as input a string depicting a date in YYYY/mm/dd
                        format and a string stating a time period in the form of "X day(s)" or
                        "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
                        that is X days or Y weeks after the initial date.
                        """

                        year, month, day = [int(each) for each in start_date.split('/')]


                        start_date_date_obj = datetime.date(year, month, day)

                        add = 1
                        string = time.split()
                        if string[1] == "days" or string[1] == "day":
                        add = int(string[0])
                        else:
                        add = (int(string[0]))*7



                        time_to_add = datetime.timedelta(days = add)

                        end_date = (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

                        return end_date





                        share|improve this answer






























                          0














                          Here's a more simple version of a previous answer. I'm a beginner so I can't understand all of the advanced code here.



                          import datetime
                          def which_date(start_date,time):
                          """
                          This function takes as input a string depicting a date in YYYY/mm/dd
                          format and a string stating a time period in the form of "X day(s)" or
                          "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
                          that is X days or Y weeks after the initial date.
                          """

                          year, month, day = [int(each) for each in start_date.split('/')]


                          start_date_date_obj = datetime.date(year, month, day)

                          add = 1
                          string = time.split()
                          if string[1] == "days" or string[1] == "day":
                          add = int(string[0])
                          else:
                          add = (int(string[0]))*7



                          time_to_add = datetime.timedelta(days = add)

                          end_date = (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

                          return end_date





                          share|improve this answer




























                            0












                            0








                            0







                            Here's a more simple version of a previous answer. I'm a beginner so I can't understand all of the advanced code here.



                            import datetime
                            def which_date(start_date,time):
                            """
                            This function takes as input a string depicting a date in YYYY/mm/dd
                            format and a string stating a time period in the form of "X day(s)" or
                            "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
                            that is X days or Y weeks after the initial date.
                            """

                            year, month, day = [int(each) for each in start_date.split('/')]


                            start_date_date_obj = datetime.date(year, month, day)

                            add = 1
                            string = time.split()
                            if string[1] == "days" or string[1] == "day":
                            add = int(string[0])
                            else:
                            add = (int(string[0]))*7



                            time_to_add = datetime.timedelta(days = add)

                            end_date = (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

                            return end_date





                            share|improve this answer















                            Here's a more simple version of a previous answer. I'm a beginner so I can't understand all of the advanced code here.



                            import datetime
                            def which_date(start_date,time):
                            """
                            This function takes as input a string depicting a date in YYYY/mm/dd
                            format and a string stating a time period in the form of "X day(s)" or
                            "Y week(s)". Output should be a string in form YYYY/mm/dd with the date
                            that is X days or Y weeks after the initial date.
                            """

                            year, month, day = [int(each) for each in start_date.split('/')]


                            start_date_date_obj = datetime.date(year, month, day)

                            add = 1
                            string = time.split()
                            if string[1] == "days" or string[1] == "day":
                            add = int(string[0])
                            else:
                            add = (int(string[0]))*7



                            time_to_add = datetime.timedelta(days = add)

                            end_date = (start_date_date_obj + time_to_add).strftime('%Y/%m/%d')

                            return end_date






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 21 '18 at 1:28









                            jdv

                            1,85632131




                            1,85632131










                            answered Dec 20 '18 at 21:37









                            Goldaaron18Goldaaron18

                            1




                            1






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53327515%2fpython-datetime-problem-is-there-a-better-solution%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                List item for chat from Array inside array React Native

                                Thiostrepton

                                Caerphilly