Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #16906 -- Format datetimes with str/unicode instead of strftime…

… where possible: it's faster and it works for all dates.

Also ensured that datetime_safe is used wherever strftime is called on dates/datetimes that may be before 1900.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@16978 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 06d9b82a27a4e47b435805938af23360e4291fb4 1 parent b784576
Aymeric Augustin authored October 13, 2011
8  django/contrib/admin/filters.py
@@ -281,9 +281,9 @@ def __init__(self, field, request, params, model, model_admin, field_path):
281 281
 
282 282
         today = datetime.date.today()
283 283
         one_week_ago = today - datetime.timedelta(days=7)
284  
-        today_str = (isinstance(self.field, models.DateTimeField)
285  
-                        and today.strftime('%Y-%m-%d 23:59:59')
286  
-                        or today.strftime('%Y-%m-%d'))
  284
+        today_str = str(today)
  285
+        if isinstance(self.field, models.DateTimeField):
  286
+            today_str += ' 23:59:59'
287 287
 
288 288
         self.lookup_kwarg_year = '%s__year' % self.field_path
289 289
         self.lookup_kwarg_month = '%s__month' % self.field_path
@@ -299,7 +299,7 @@ def __init__(self, field, request, params, model, model_admin, field_path):
299 299
                 self.lookup_kwarg_day: str(today.day),
300 300
             }),
301 301
             (_('Past 7 days'), {
302  
-                self.lookup_kwarg_past_7_days_gte: one_week_ago.strftime('%Y-%m-%d'),
  302
+                self.lookup_kwarg_past_7_days_gte: str(one_week_ago),
303 303
                 self.lookup_kwarg_past_7_days_lte: today_str,
304 304
             }),
305 305
             (_('This month'), {
7  django/contrib/auth/tokens.py
@@ -52,14 +52,13 @@ def _make_token_with_timestamp(self, user, timestamp):
52 52
         # invalid as soon as it is used.
53 53
         # We limit the hash to 20 chars to keep URL short
54 54
         key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
55  
-        value = unicode(user.id) + \
56  
-            user.password + user.last_login.strftime('%Y-%m-%d %H:%M:%S') + \
57  
-            unicode(timestamp)
  55
+        value = (unicode(user.id) + user.password +
  56
+                unicode(user.last_login) + unicode(timestamp))
58 57
         hash = salted_hmac(key_salt, value).hexdigest()[::2]
59 58
         return "%s-%s" % (ts_b36, hash)
60 59
 
61 60
     def _num_days(self, dt):
62  
-        return (dt - date(2001,1,1)).days
  61
+        return (dt - date(2001, 1, 1)).days
63 62
 
64 63
     def _today(self):
65 64
         # Used for mocking in tests
8  django/contrib/sitemaps/tests/basic.py
@@ -67,7 +67,7 @@ def test_simple_sitemap(self):
67 67
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
68 68
 <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
69 69
 </urlset>
70  
-""" % (self.base_url, date.today().strftime('%Y-%m-%d')))
  70
+""" % (self.base_url, date.today()))
71 71
 
72 72
     def test_simple_custom_sitemap(self):
73 73
         "A simple sitemap can be rendered with a custom template"
@@ -79,7 +79,7 @@ def test_simple_custom_sitemap(self):
79 79
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
80 80
 <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
81 81
 </urlset>
82  
-""" % (self.base_url, date.today().strftime('%Y-%m-%d')))
  82
+""" % (self.base_url, date.today()))
83 83
 
84 84
     @skipUnless(settings.USE_I18N, "Internationalization is not enabled")
85 85
     def test_localized_priority(self):
@@ -93,7 +93,7 @@ def test_localized_priority(self):
93 93
         # haven't been rendered in localized format
94 94
         response = self.client.get('/simple/sitemap.xml')
95 95
         self.assertContains(response, '<priority>0.5</priority>')
96  
-        self.assertContains(response, '<lastmod>%s</lastmod>' % date.today().strftime('%Y-%m-%d'))
  96
+        self.assertContains(response, '<lastmod>%s</lastmod>' % date.today())
97 97
         deactivate()
98 98
 
99 99
     def test_generic_sitemap(self):
@@ -152,7 +152,7 @@ def test_requestsite_sitemap(self):
152 152
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
153 153
 <url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
154 154
 </urlset>
155  
-""" % date.today().strftime('%Y-%m-%d'))
  155
+""" % date.today())
156 156
 
157 157
     @skipUnless("django.contrib.sites" in settings.INSTALLED_APPS, "django.contrib.sites app not installed.")
158 158
     def test_sitemap_get_urls_no_site_1(self):
5  django/db/backends/__init__.py
@@ -9,7 +9,6 @@
9 9
 from django.db import DEFAULT_DB_ALIAS
10 10
 from django.db.backends import util
11 11
 from django.db.transaction import TransactionManagementError
12  
-from django.utils import datetime_safe
13 12
 from django.utils.importlib import import_module
14 13
 
15 14
 
@@ -718,7 +717,7 @@ def value_to_db_date(self, value):
718 717
         """
719 718
         if value is None:
720 719
             return None
721  
-        return datetime_safe.new_date(value).strftime('%Y-%m-%d')
  720
+        return unicode(value)
722 721
 
723 722
     def value_to_db_datetime(self, value):
724 723
         """
@@ -731,7 +730,7 @@ def value_to_db_datetime(self, value):
731 730
 
732 731
     def value_to_db_time(self, value):
733 732
         """
734  
-        Transform a datetime value to an object compatible with what is expected
  733
+        Transform a time value to an object compatible with what is expected
735 734
         by the backend driver for time columns.
736 735
         """
737 736
         if value is None:
11  django/db/backends/sqlite3/base.py
@@ -320,14 +320,9 @@ def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
320 320
             dt = dt - delta
321 321
     except (ValueError, TypeError):
322 322
         return None
323  
-
324  
-    if isinstance(dt, datetime.datetime):
325  
-        rv = dt.strftime("%Y-%m-%d %H:%M:%S")
326  
-        if dt.microsecond:
327  
-            rv = "%s.%0.6d" % (rv, dt.microsecond)
328  
-    else:
329  
-        rv = dt.strftime("%Y-%m-%d")
330  
-    return rv
  323
+    # typecast_timestamp returns a date or a datetime without timezone.
  324
+    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
  325
+    return str(dt)
331 326
 
332 327
 def _sqlite_regexp(re_pattern, re_string):
333 328
     try:
8  django/db/models/fields/__init__.py
@@ -16,7 +16,6 @@
16 16
 from django.utils.text import capfirst
17 17
 from django.utils.translation import ugettext_lazy as _
18 18
 from django.utils.encoding import smart_unicode, force_unicode, smart_str
19  
-from django.utils import datetime_safe
20 19
 from django.utils.ipv6 import clean_ipv6_address
21 20
 
22 21
 class NOT_PROVIDED:
@@ -725,7 +724,7 @@ def value_to_string(self, obj):
725 724
         if val is None:
726 725
             data = ''
727 726
         else:
728  
-            data = datetime_safe.new_date(val).strftime("%Y-%m-%d")
  727
+            data = str(val)
729 728
         return data
730 729
 
731 730
     def formfield(self, **kwargs):
@@ -803,8 +802,7 @@ def value_to_string(self, obj):
803 802
         if val is None:
804 803
             data = ''
805 804
         else:
806  
-            d = datetime_safe.new_datetime(val)
807  
-            data = d.strftime('%Y-%m-%d %H:%M:%S')
  805
+            data = str(val.replace(microsecond=0, tzinfo=None))
808 806
         return data
809 807
 
810 808
     def formfield(self, **kwargs):
@@ -1234,7 +1232,7 @@ def value_to_string(self, obj):
1234 1232
         if val is None:
1235 1233
             data = ''
1236 1234
         else:
1237  
-            data = val.strftime("%H:%M:%S")
  1235
+            data = str(val.replace(microsecond=0))
1238 1236
         return data
1239 1237
 
1240 1238
     def formfield(self, **kwargs):
6  tests/regressiontests/admin_filters/tests.py
@@ -188,8 +188,8 @@ def test_datefieldlistfilter(self):
188 188
         self.assertEqual(choice['query_string'], '?date_registered__year=%s'
189 189
                                                 % (self.today.year))
190 190
 
191  
-        request = self.request_factory.get('/', {'date_registered__gte': self.one_week_ago.strftime('%Y-%m-%d'),
192  
-                                                 'date_registered__lte': self.today.strftime('%Y-%m-%d')})
  191
+        request = self.request_factory.get('/', {'date_registered__gte': str(self.one_week_ago),
  192
+                                                 'date_registered__lte': str(self.today)})
193 193
         changelist = self.get_changelist(request, Book, modeladmin)
194 194
 
195 195
         # Make sure the correct queryset is returned
@@ -203,7 +203,7 @@ def test_datefieldlistfilter(self):
203 203
         self.assertEqual(choice['selected'], True)
204 204
         self.assertEqual(choice['query_string'], '?date_registered__gte=%s'
205 205
                                                  '&date_registered__lte=%s'
206  
-                                                % (self.one_week_ago.strftime('%Y-%m-%d'), self.today.strftime('%Y-%m-%d')))
  206
+                                                % (str(self.one_week_ago), str(self.today)))
207 207
 
208 208
     def test_allvaluesfieldlistfilter(self):
209 209
         modeladmin = BookAdmin(Book, site)

0 notes on commit 06d9b82

Please sign in to comment.
Something went wrong with that request. Please try again.