Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allowing invalid dates in python datetime

The datetime module does date validation and math which is fine when you care about reality.

I need an object that holds dates generated even if they were invalid. Date time is way too strict as sometimes I know year only or year and month only and sometimes I have a date like 2011-02-30.

Is there a module out there that is like datetime but that can handle invalid dates?

If not, what's the best way to handle this while duplicating as little functionality as possible and still allowing date math when it is possible to perform?

UPDATE

Motivation for this is integration with multiple systems that use dates and don't care about invalid dates (mysql and perl) in addition to wanting the ability to tell basic general ranges of time. For fuzzy date math start from the beginning of the known unit of time (if I know year and month but not day, use the first, if i know year but no month or day, use january first). This last bit is not necessary but would be nice and I get why it is not common as people who need special case date math will probably build it themselves.

One of the major issues I have is loading dates from mysql into python using sqlalchemy and mysqldb -- if you load a value from a date column im mysql that looks like '2011-01-00' in mysql, you get None in python. This is not cool by any stretch.

like image 337
underrun Avatar asked Jul 14 '11 17:07

underrun


1 Answers

If the datetime module is too strict, store it as a string or a tuple padded with zero's for unknown values.

Edit if you're having trouble translating from mysql to python, write yourself an adapter class to do the conversion in a safe way (See Changing attribute behaviour).

Edit2 a simple alternative might be to write a short script to run through all your SQL dates and do the corrections there i.e. change 2011-01-00 to 2011-01-01

Edit3 The docs suggest you can override reflected columns so you could treat your timestamp columns as strings ...or in later versions of SQLAlchemy, you can use the column_property for overrides.

like image 161
Jon Cage Avatar answered Oct 06 '22 11:10

Jon Cage