Revision: 6500
Author:   russblau
Date:     2009-03-08 11:55:20 +0000 (Sun, 08 Mar 2009)

Log Message:
-----------
Add a class for handling timestamp conversions, in place of functions.

Modified Paths:
--------------
    branches/rewrite/pywikibot/__init__.py
    branches/rewrite/pywikibot/data/logentries.py
    branches/rewrite/pywikibot/date.py
    branches/rewrite/pywikibot/site.py

Modified: branches/rewrite/pywikibot/__init__.py
===================================================================
--- branches/rewrite/pywikibot/__init__.py      2009-03-08 09:12:46 UTC (rev 
6499)
+++ branches/rewrite/pywikibot/__init__.py      2009-03-08 11:55:20 UTC (rev 
6500)
@@ -9,6 +9,7 @@
 #
 __version__ = '$Id$'
 
+import datetime
 import difflib
 import logging
 import re
@@ -22,6 +23,56 @@
 logging.basicConfig(fmt="%(message)s")
 
 
+class Timestamp(datetime.datetime):
+    """Class for handling Mediawiki timestamps.
+
+    This inherits from datetime.datetime, so it can use all of the methods
+    and operations of a datetime object.  To ensure that the results of any
+    operation are also a Timestamp object, be sure to use only Timestamp
+    objects (and datetime.timedeltas) in any operation.
+
+    Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to
+    create Timestamp objects from Mediawiki string formats.
+
+    Use Timestamp.utcnow() [not .now()] for the current time.
+
+    """
+    mediawikiTSFormat = "%Y%m%d%H%M%S"
+    ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
+
+    @classmethod
+    def fromISOformat(cls, ts):
+        """Convert an ISO 8601 timestamp to a Timestamp object."""
+        return cls.strptime(ts, cls.ISO8601Format)
+
+    @classmethod
+    def fromtimestampformat(cls, ts):
+        """Convert the internal MediaWiki timestamp format to a Timestamp 
object."""
+        return cls.strptime(ts, cls.mediawikiTSFormat)
+
+    def __str__(self):
+        """Return a string format recognized by the API"""
+        return self.strftime(self.ISO8601Format)
+
+    def __add__(self, other):
+        newdt = datetime.datetime.__add__(self, other)
+        if isinstance(newdt, datetime.datetime):
+            return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
+                             newdt.minute, newdt.second, newdt.microsecond,
+                             newdt.tzinfo)
+        else:
+            return newdt
+
+    def __sub__(self, other):
+        newdt = datetime.datetime.__sub__(self, other)
+        if isinstance(newdt, datetime.datetime):
+            return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
+                             newdt.minute, newdt.second, newdt.microsecond,
+                             newdt.tzinfo)
+        else:
+            return newdt
+
+
 def deprecated(instead=None):
     """Decorator to output a method deprecation warning.
 

Modified: branches/rewrite/pywikibot/data/logentries.py
===================================================================
--- branches/rewrite/pywikibot/data/logentries.py       2009-03-08 09:12:46 UTC 
(rev 6499)
+++ branches/rewrite/pywikibot/data/logentries.py       2009-03-08 11:55:20 UTC 
(rev 6500)
@@ -67,9 +67,10 @@
         return self.data['user']
 
     def timestamp(self):
-        """datetime object corresponding to event timestamp"""
+        """Timestamp object corresponding to event timestamp"""
         if not hasattr(self, '_timestamp'):
-            self._timestamp = date.ISO2datetime(self.data['timestamp'])
+            self._timestamp = pywikibot.Timestamp.fromISOformat(
+                                            self.data['timestamp'])
         return self._timestamp
 
     def comment(self):
@@ -138,12 +139,13 @@
 
     def expiry(self):
         """
-        Returns a datetime.datetime representing the block expiry date
+        Returns a Timestamp representing the block expiry date
         Raises an Error if the entry is an unblocking log entry
         """
         if hasattr(self, '_expiry'):
             return self._expiry
-        self._expiry = date.ISO2datetime(self._getBlockDetails()['expiry'])
+        self._expiry = pywikibot.Timestamp.fromISOformat(
+                                    self._getBlockDetails()['expiry'])
         return self._expiry
 
 class ProtectEntry(LogEntry):

Modified: branches/rewrite/pywikibot/date.py
===================================================================
--- branches/rewrite/pywikibot/date.py  2009-03-08 09:12:46 UTC (rev 6499)
+++ branches/rewrite/pywikibot/date.py  2009-03-08 11:55:20 UTC (rev 6500)
@@ -1509,19 +1509,6 @@
     else:
         return formats['YearAD'][lang](year)
 
-mediawikiTSFormat = "%Y%m%d%H%M%S"
-ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
-def timestamp2datetime(ts):
-    from datetime import datetime
-    return datetime.strptime(ts, mediawikiTSFormat)
-
-def datetime2timestamp(dt):
-    return dt.strftime(mediawikiTSFormat)
-
-def ISO2datetime(ts):
-    from datetime import datetime
-    return datetime.strptime(ts, ISO8601Format)
-
 #
 #
 #  Map testing methods

Modified: branches/rewrite/pywikibot/site.py
===================================================================
--- branches/rewrite/pywikibot/site.py  2009-03-08 09:12:46 UTC (rev 6499)
+++ branches/rewrite/pywikibot/site.py  2009-03-08 11:55:20 UTC (rev 6500)
@@ -790,10 +790,9 @@
         return re.search('\d+', result['parse']['text']['*']).group()
 
     def getcurrenttime(self):
-        """Returns a datetime object representing server time"""
+        """Returns a Timestamp object representing server time"""
         ts = self.getcurrenttimestamp()
-        from date import timestamp2datetime
-        return timestamp2datetime(ts)
+        return pywikibot.Timestamp.fromtimestampformat(ts)
 
     def _getsiteinfo(self):
         """Retrieve siteinfo and namespaces from site."""



_______________________________________________
Pywikipedia-l mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/pywikipedia-l

Reply via email to