Size: 3515
Comment:
|
Size: 3531
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 95: | Line 95: |
By it's very nature this method cannot work. Is 01/01/2000 MM/DD/YYYY or DD/MM/YYYY? |
By it's very nature this method cannot work. Is 01/01/2000 the date format MM/DD/YYYY or DD/MM/YYYY? |
Date/Time Conversion
import re from datetime import datetime class DateUtils(object): __DATE_REGEX = r"[/.]+" __dateRegex = re.compile(__DATE_REGEX) __YMD = "yyyy-mm-dd hh:mm:ss" __MDY = "mm-dd-yyyy hh:mm:ss" __DMY = "dd-mm-yyyy hh:mm:ss" __YMD_NON_DLM = "yyyymmddHHMMSS" def __transposeFromYMDHMS(self, value): size = len(value) y = value[:4] m = value[5:7] d = value[8:10] H = M = S = 0 if size >= 13: H = value[11:13] if size >= 16: M = value[14:16] if size >= 19: S = value[17:] return "%s-%s-%s %02i:%02i:%02i" % (y, m, d, H, M, S) def __transposeFromMDYHMS(self, value): size = len(value) m = value[:2] d = value[3:5] y = value[6:10] H = M = S = 0 if size >= 13: H = value[11:13] if size >= 16: M = value[14:16] if size >= 19: S = value[17:] return "%s-%s-%s %02i:%02i:%02i" % (y, m, d, H, M, S) def __transposeFromDMYHMS(self, value): size = len(value) d = value[:2] m = value[3:5] y = value[6:10] H = M = S = 0 if size >= 13: H = value[11:13] if size >= 16: M = value[14:16] if size >= 19: S = value[17:] return "%s-%s-%s %02i:%02i:%02i" % (y, m, d, H, M, S) def __transposeNonDelimiterYMDHMS(self, value): size = len(value) y = value[:4] m = value[4:6] d = value[6:8] H = M = S = 0 if size >= 10: H = value[8:10] if size >= 12: M = value[10:12] if size >= 14: S = value[12:] return "%s-%s-%s %02i:%02i:%02i" % (y, m, d, H, M, S) __FROM_DATE_FORMATS = {__YMD: __transposeFromYMDHMS, __MDY: __transposeFromMDYHMS, __DMY: __transposeFromDMYHMS, __YMD_NON_DLM: __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. """ fmt = self.__dateRegex.sub('-', format) try: value = self.__FROM_DATE_FORMATS[fmt](self, value) date, time = value.split(' ') except KeyError, e: msg = "Invalid date format should be one of %s." raise KeyError(msg % self.__FROM_DATE_FORMATS.keys()) 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" % \ (fmt, value, e) raise Exception(msg) @classmethod def _snoopDateFormat(self, value): """ By it's very nature this method cannot work. Is 01/01/2000 the date format MM/DD/YYYY or DD/MM/YYYY? """ fmt = None delim = any([char for char in value if char in ('-', '.', '/', ':')]) year = value[:4].isdigit() if year and not delim: fmt = self.__YMD_NON_DLM elif year and delim: fmt = self.__YMD else: pass # Cannot determine the else. return fmt