⇤ ← Revision 1 as of 2009-04-10 19:05:00
Size: 2621
Comment:
|
Size: 2642
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 26: | Line 26: |
value = "%s-%s-%s" % (y, m, d) | value = "%s-%s-%s 00:00:00" % (y, m, d) |
Line 38: | Line 38: |
value = "%s-%s-%s" % (y, m, d) | value = "%s-%s-%s 00:00:00" % (y, m, d) |
Line 53: | Line 53: |
value = "%s-%s-%s %s:%s" % (y, m, d, H, M) | value = "%s-%s-%s %s:%s:00" % (y, m, d, H, M) |
Date/Time Conversion
import re from datetime import datetime class BaseUtils(object): __DATE_REGEX = r"[/.]+" __dateRegex = re.compile(__DATE_REGEX) def __init__(self): pass def __transposeFromYMDHMS(self, value): return value def __transposeFromMDYHMS(self, value): m = value[:2] d = value[3:5] y = value[6:10] if len(value) > 10: value = "%s-%s-%s %s" % (y, m, d, value[11:]) else: value = "%s-%s-%s 00:00:00" % (y, m, d) return value def __transposeFromDMYHMS(self, value): d = value[:2] m = value[3:5] y = value[6:10] if len(value) > 10: value = "%s-%s-%s %s" % (y, m, d, value[11:]) else: value = "%s-%s-%s 00:00:00" % (y, m, d) return value def __transposeNonDelimiterYMDHMS(self, value): y = value[:4] m = value[4:6] d = value[6:8] H = value[8:10] M = value[10:12] if len(value) > 12: S = value[12:] value = "%s-%s-%s %s:%s:%s" % (y, m, d, H, M, S) else: value = "%s-%s-%s %s:%s:00" % (y, m, d, H, M) return value __FROM_DATE_FORMATS = {'yyyy-mm-dd hh:mm:ss': __transposeFromYMDHMS, 'mm-dd-yyyy hh:mm:ss': __transposeFromMDYHMS, 'dd-mm-yyyy hh:mm:ss': __transposeFromDMYHMS, 'yyyymmddHHMMSS': __transposeNonDelimiterYMDHMS} @classmethod def toDatetime(self, value, format='yyyy-mm-dd hh:mm:ss'): """ Convert a string representation of a date and time to a python datetime object. @param value: The string value to convert. @keyword format: The format to convert from. @return: A Python datetime object. """ format = self.__dateRegex.sub('-', format) try: value = self.__FROM_DATE_FORMATS[format](self, value) date, time = value.split(' ') except KeyError, e: msg = "Invalid date format should be one of %s." % \ self.__FROM_DATE_FORMATS.keys() raise KeyError(msg) try: return datetime(*[int(float(x)) for x in date.split("-")] + [int(float(x)) for x in time.split(":")]) except Exception, e: msg = "Invalid format for datetime %s, found: %s, %s" % \ (format, value, e) raise Exception(msg)