Skip to content Skip to sidebar Skip to footer

Valueerror: Day Is Out Of Range For Month Datetime

I have run into a problem with some code I have been writing. I take in four inputs ( day, month and year ) as a date, and times for how many times they want to repeat the task ( e

Solution 1:

There are several reasons why incrementing the components of a datetime and then creating a new one is not a good idea. Primarily because dealing with the Gregorian calendar yourself isn't that enjoyable IMHO, and datetime objects can do it for you.

On that note, a much more straightforward approach would be to add a timedelta to your datetime within the loop. For instance,

>>> from datetime import timedelta
>>> times = 4>>> cur_date = datetime.date(2017, 2, 24)

>>> for _ inrange(times):
        print('today is {0}, do something'.format(cur_date))
        cur_date += timedelta(days=7)

today is2017-02-24, do something
today is2017-03-03, do something
today is2017-03-10, do something
today is2017-03-17, do something

This could be placed in a generator as well, depending on your use case.

>>>for dt in (cur_date + timedelta(days=x*7) for x in range(times)):
        print('today is {0}, do something'.format(dt))

today is2017-02-24, do something
today is2017-03-03, do something
today is2017-03-10, do something
today is2017-03-17, do something

or with Pandas pd.date_range

>>> import pandas as pd
>>> list(pd.date_range(start='2017-02-24', periods=4, freq='7D'))

[Timestamp('2017-02-24 00:00:00', freq='7D'),
 Timestamp('2017-03-03 00:00:00', freq='7D'),
 Timestamp('2017-03-10 00:00:00', freq='7D'),
 Timestamp('2017-03-17 00:00:00', freq='7D')]

Now what would happen if you attempted this example with your approach?

>>>year, month, day=2017, 2, 24>>>for i inrange(0 , times):
        day=day
        fulldateadd = datetime.date(year, month, day)
        print('today is {0}, do something'.format(fulldateadd))
        day=day+7
        if day>31:
            day=day-31month=month+1

today is2017-02-24, do something

ValueErrorTraceback (most recent calllast)
<ipython-input-255-7df608ebbf8e>in<module>()
      1for i inrange(0 , times):
      2day=day----> 3     fulldateadd = datetime.date(year, month, day)4     print('today is {0}, do something'.format(fulldateadd))
      5day=day+7

ValueError: dayisoutofrangeformonth

February doesn't have 31 days... so you would have to include a check with a mapping to the number of days in each month. Including logic for leap years.

Post a Comment for "Valueerror: Day Is Out Of Range For Month Datetime"