How can I parse this correctly?

Tim Chase python.list at tim.thechases.com
Sun Apr 6 08:31:05 EDT 2014


On 2014-04-06 14:21, Ben Finney wrote:
> I assume you mean you will be creating ‘datetime.date’ objects. What
> will you set as the month and day?
> 
> Alternatively, if you just want to do integer arithmetic on the
> year, you don't need the ‘datetime’ module at all.

Even if you do the arithmetic by hand, it's still nice to use the
datetime module to parse for sane dates:

  year = 2004
  month = 2
  day = 29

what should month & day be if you increment/decrement the year by
one?  The datetime module will throw a ValueError which is a nice
check for a valid date.  I've had to do things like this in a loop to
sanitize dates (depending on which field is being inc/dec'ed, by how
much, and which direction it's going) and it's nice to just have a

  y,m,d = initial = some_date.timetuple()[:3] #
  result = None
  while result is None:
    y,m,d = twiddle(y, m, d)
    try:
      result = datetime(y, m, d)
    except ValueError:
      result = None
  log.info("Shifted %r -> %r", initial, result)

where twiddle() is whatever business logic I need for this particular
case.  For me usually, it's adjusting by one month for billing
purposes.

-tkc





More information about the Python-list mailing list