Avoid strftime when isoformat can do the job
|Reported by:||aaugustin||Owned by:||nobody|
|Cc:||Triage Stage:||Ready for checkin|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by aaugustin)
While working on timezone support in Django, the inconsistency in these three functions surprised me: https://code.djangoproject.com/browser/django/trunk/django/db/backends/__init__.py#L714
In fact, r7946 introduced a datetime_safe module that provides a Python implementation of datetime.[date|datetime].strftime for dates before 1900.
However, this is overkill for the purpose of just showing a date or datetime in ISO format (%Y-%m-%d and %Y-%m-%d %H:%M:%S). It makes the code needlessly complicated, sometimes inconistent, and inefficient. The isoformat method achieves the same result, works for any date, and is implemented in C.
Also, some code still uses the strftime function from the standard library. Using isoformat is better because it isn't subject to the 1900 limit.
See attached patch.
For more background, see isoformat_date in http://svn.python.org/view/python/tags/r271/Modules/datetimemodule.c?view=markup. Note that date objects have no __unicode__ and their __str__ just call isoformat, so str(date) or unicode(date) is the same as datetime_safe.date(date.year, date.month, date.day).strftime('%Y-%m-%d'). It's pretty much the same for datetime objects, except that isoformat uses T as a separator, while str and unicode use a space.
Changing date.format('%Y-%m-%d') to date.isoformat() is safe. Changing datetime.format('%Y-%m-%d %H:%M:%S') to datetime.isoformat() requires removing the microseconds and the timezone first, if there is one, so the correct pattern is datetime.replace(microsecond=0, tzinfo=None). This also applies for time objects.
Change History (4)
Changed 2 years ago by aaugustin
comment:2 Changed 2 years ago by lukeplant
- Triage Stage changed from Unreviewed to Ready for checkin