Differences between revisions 2 and 22 (spanning 20 versions)
Revision 2 as of 2009-04-10 19:08:28
Size: 2642
Editor: CarlNobile
Comment:
Revision 22 as of 2010-12-23 04:49:47
Size: 2430
Editor: CarlNobile
Comment:
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
[[attachment:dateutils.py|Download DateUtils]]

This utility class will convert different date time formats into the proper format to create a Python {{{datetime}}} object. It will use the current locale to determine differences that can not be determined in any other way such as 05/12/2010 meaning either dd/mm/yyyy or mm/dd/yyyy.

'''Methods'''

 1. DateUtils.toDatetime(value, format=None)
 1. DateUtils.getFormatTypes()
 1. DateUtils.isValidDate(dObj)
 1. DateUtils.isValidTime(tObj)
 1. DateUtils.isValidDateTime(dtObj)

The methods are all classmethods.

A string value is passed into the {{{DateUtils.toDatetime()}}} method. If you know the format of your date or only want to allow a specific format that format can be passed into the {{{format}}} keyword argument.

== Implemented Formats ==
 1. yyyy-mm-dd hh:mm:ss (with or without milliseconds)
 1. mm-dd-yyyy hh:mm:ss (with or without milliseconds)
 1. dd-mm-yyyy hh:mm:ss (with or without milliseconds)
 1. yyyymmddHHMMSS (with or without milliseconds)
 1. wkday, dd month yyyy hh:mm:ss GMT
 1. weekday, dd-month-yy hh:mm:ss GMT
 1. wkday month dd hh:mm:ss yyyy

The last three are RFC-2616 valid formats that can be used in HTTP headers such as {{{Last-Modified}}} or {{{If-Modified-Since}}}. The datetime object generated can be used to compare for conditional GETs. The datetime objects that are generated for the RFC-2616 formats are timezone naive since all headers are in GMT (UTC) time and can be compared as is. Conversions to and from different timezones should be done beforehand with a tool like [[http://pytz.sourceforge.net/|pytz]].

=== Examples ===

 - Date but no time
Line 4: Line 35:
import re
from datetime import datetime
from dateutils import DateUtils
Line 7: Line 37:
DateUtils.toDatetime('2010/04/05')
Out[2]: datetime.datetime(2010, 4, 5, 0, 0)
}}}
Line 8: Line 41:
class BaseUtils(object):
    __DATE_REGEX = r"[/.]+"
    __dateRegex = re.compile(__DATE_REGEX)
 - Date and Time
Line 12: Line 43:
    def __init__(self):
        pass
{{{
from dateutils import DateUtils
Line 15: Line 46:
    def __transposeFromYMDHMS(self, value):
        return value
DateUtils.toDatetime('2010/04/05 23:20:59')
Out[3]: datetime.datetime(2010, 4, 5, 23, 20, 59)
}}}
Line 18: Line 50:
    def __transposeFromMDYHMS(self, value):
        m = value[:2]
        d = value[3:5]
        y = value[6:10]
 - Date, Time and the format is specified.
Line 23: Line 52:
        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)
{{{
from dateutils import DateUtils
Line 28: Line 55:
        return value DateUtils.toDatetime('20100405232059', format="yyyymmddHHMMSS")
Out[6]: datetime.datetime(2010, 4, 5, 23, 20, 59)
}}}
Line 30: Line 59:
    def __transposeFromDMYHMS(self, value):
        d = value[:2]
        m = value[3:5]
        y = value[6:10]
== Exceptions ==
Line 35: Line 61:
        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)
}}}
 1. A {{{ValueError}}} will be raised if the value does not match the format or if the format can not be determined.
 1. A {{{KeyError}}} will be raised if the the date time format is not supported.

Date/Time Conversion

Download DateUtils

This utility class will convert different date time formats into the proper format to create a Python datetime object. It will use the current locale to determine differences that can not be determined in any other way such as 05/12/2010 meaning either dd/mm/yyyy or mm/dd/yyyy.

Methods

  1. DateUtils.toDatetime(value, format=None)

  2. DateUtils.getFormatTypes()

  3. DateUtils.isValidDate(dObj)

  4. DateUtils.isValidTime(tObj)

  5. DateUtils.isValidDateTime(dtObj)

The methods are all classmethods.

A string value is passed into the DateUtils.toDatetime() method. If you know the format of your date or only want to allow a specific format that format can be passed into the format keyword argument.

Implemented Formats

  1. yyyy-mm-dd hh:mm:ss (with or without milliseconds)
  2. mm-dd-yyyy hh:mm:ss (with or without milliseconds)
  3. dd-mm-yyyy hh:mm:ss (with or without milliseconds)
  4. yyyymmddHHMMSS (with or without milliseconds)
  5. wkday, dd month yyyy hh:mm:ss GMT
  6. weekday, dd-month-yy hh:mm:ss GMT
  7. wkday month dd hh:mm:ss yyyy

The last three are RFC-2616 valid formats that can be used in HTTP headers such as Last-Modified or If-Modified-Since. The datetime object generated can be used to compare for conditional GETs. The datetime objects that are generated for the RFC-2616 formats are timezone naive since all headers are in GMT (UTC) time and can be compared as is. Conversions to and from different timezones should be done beforehand with a tool like pytz.

Examples

  • - Date but no time

from dateutils import DateUtils

DateUtils.toDatetime('2010/04/05')
Out[2]: datetime.datetime(2010, 4, 5, 0, 0)
  • - Date and Time

from dateutils import DateUtils

DateUtils.toDatetime('2010/04/05 23:20:59')
Out[3]: datetime.datetime(2010, 4, 5, 23, 20, 59)
  • - Date, Time and the format is specified.

from dateutils import DateUtils

DateUtils.toDatetime('20100405232059', format="yyyymmddHHMMSS")
Out[6]: datetime.datetime(2010, 4, 5, 23, 20, 59)

Exceptions

  1. A ValueError will be raised if the value does not match the format or if the format can not be determined.

  2. A KeyError will be raised if the the date time format is not supported.

datetimeConversion (last edited 2010-12-23 04:49:47 by CarlNobile)