72496

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 ( eg. every Monday for 3 weeks ). The code is great however if the weeks differ between months I get this error:

File "C:\Users\dansi\AppData\Local\Programs\Python\Python36-32\gui test 3.py", line 72, in addtimeslot fulldateadd = datetime.date(year, month, day) ValueError: day is out of range for month

Part of code that is relevant:

for i in range(0 , times): fulldateadd = datetime.date(year, month, day) cursor.execute( '''INSERT INTO dates (Date, Name, Start, End) VALUES( ?,?,?,? );''', (fulldateadd , name1, starttimehour, endtimehour)) day = day + 7 if day > 31: month = month + 1

I've tried to increment the month when the number of days are more than 31 however it doesn't seem to work.

Answer1:

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 _ in range(times): print('today is {0}, do something'.format(cur_date)) cur_date += timedelta(days=7) today is 2017-02-24, do something today is 2017-03-03, do something today is 2017-03-10, do something today is 2017-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 is 2017-02-24, do something today is 2017-03-03, do something today is 2017-03-10, do something today is 2017-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')] <hr>

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

>>> year, month, day = 2017, 2, 24 >>> for i in range(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 - 31 month = month + 1 today is 2017-02-24, do something ValueErrorTraceback (most recent call last) <ipython-input-255-7df608ebbf8e> in <module>() 1 for i in range(0 , times): 2 day = day ----> 3 fulldateadd = datetime.date(year, month, day) 4 print('today is {0}, do something'.format(fulldateadd)) 5 day = day + 7 ValueError: day is out of range for month

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.

Recommend

  • Query timeout expired in django-mssql when executing custom SQL directly
  • OpenOptionsMenu not working with ActionBarSherlock Custom SubMenu
  • Convert C# statements including NSubstitute code to VB.net
  • C# 4 and CLR Compatibility
  • RabbitMQ java client stops consuming messages
  • java.lang.IndexOutOfBoundsException occuring on ArrayList
  • Prolog Ambiguous Output
  • How gzip file gets stored in HDFS
  • Pre-populated SQLite Database not reading properly in Android Studio
  • my tic-tac-toe program in matlab does not work [closed]
  • Converting query results into DataFrame in python
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • Python 3.2.2, error(scripts to exe)
  • Using Generics on right hand side in Java 6?
  • Why must we declare a variable name when adding a method to a struct in Golang?
  • How to use function wrapper in mustache.php?
  • Python ImageIO Gif Set Delay Between Frames
  • Possible to get mouse events fired when cursor is outside page?
  • pillow imaging ImportError
  • Security issues with PHP's Readfile method
  • MySQL Order by column = x, column asc?
  • Calling Worksheet functions from vba in foreign language versions of Excel
  • Excel's Macro-Recorder usage
  • Django simple Captcha “No module named fields” error
  • onBackPressed() not being executed
  • Textfile Structure (tables)
  • How to know when stdin is empty if it contains EOF?
  • Using $this when not in object context
  • PHP - How to update data to MySQL when click a radio button
  • req.body is undefined - nodejs
  • How do I fake an specific browser client when using Java's Net library?
  • How reduce the height of an mschart by breaking up the y-axis
  • Join two tables and save into third-sql
  • Perl system calls when running as another user using sudo
  • How to handle AllServersUnavailable Exception
  • VBA Convert delimiter text file to Excel
  • Delete MySQLi record without showing the id in the URL
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Programmatically clearing map cache
  • Reading document lines to the user (python)