Returns a datetime object with optional params or today.
553518
def _get_date(day=None, month=None, year=None):
    """"""

    now = datetime.date.today()
    if day is None:
        return now

    try:
        return datetime.date(
            day=int(day),
            month=int(month or now.month),
            year=int(year or now.year),
        )
    except ValueError as error:
        print("error: {0}".format(error), file=sys.stderr)
819375
def get_dated_items(self):
        
        now = timezone.now()
        if timezone.is_aware(now):
            now = timezone.localtime(now)
        today = now.date()
        self.year, self.month, self.day = today.isoformat().split('-')
        return self._get_dated_items(today)
822975
def datetime(self):
        
        date_string = '%s %s' % (self._date, self._time.upper())
        date_string = re.sub(r'/.*', '', date_string)
        date_string = re.sub(r' ET', '', date_string)
        date_string += 'M'
        date_string = re.sub(r'PMM', 'PM', date_string, flags=re.IGNORECASE)
        date_string = re.sub(r'AMM', 'AM', date_string, flags=re.IGNORECASE)
        date_string = re.sub(r' PM', 'PM', date_string, flags=re.IGNORECASE)
        date_string = re.sub(r' AM', 'AM', date_string, flags=re.IGNORECASE)
        return datetime.strptime(date_string, '%a, %b %d, %Y %I:%M%p')
555898
def datetime(self):
        
        date_string = '%s %s %s' % (self._day,
                                    self._date,
                                    self._year)
        return datetime.strptime(date_string, '%a %B %d %Y')
965560
def to_datetime(arg):
    


    if isinstance(arg, datetime.datetime):
        return arg
    elif arg == 0:
        return datetime.datetime.now()
    elif isinstance(arg, str):
        if arg == "now":
            arg = datetime.datetime.now()
        elif arg == "?":
            arg = datetime.datetime(1970, 1, 1)
        else:
            arg = str2dt(arg)
    elif isinstance(arg, datetime.date):
        arg = date2datetime(arg)
    elif isinstance(arg, (int, float)):
        # Suppose it is a timestamp
        arg = ts2dt(arg)
    else:
        raise TypeError("Wrong type for argument 'arg': {}".format(arg.__class__.__name__))

    return arg
186066
def date(self) -> Optional[DateHeader]:
        """"""
        try:
            return cast(DateHeader, self[b'date'][0])
        except (KeyError, IndexError):
            return None
1218597
def _make_datetime(s):
    """
    s = bytearray(s)  # For Python 2
    year, month, day, hour, minute, second, cs = s
    if year < 70:
        year += 100
    return datetime(1900 + year, month, day, hour, minute, second, 10000 * cs)
835325
def format(date, now=None, locale='en'):
    '''
    
    '''
    if not isinstance(date, timedelta):
        if now is None:
            now = datetime.now()
        date = parser.parse(date)
        now = parser.parse(now)

        if date is None:
            raise ParameterUnvalid('the parameter `date` should be datetime '
                                   '/ timedelta, or datetime formated string.')
        if now is None:
            raise ParameterUnvalid('the parameter `now` should be datetime, '
                                   'or datetime formated string.')
        date = now - date
    # the gap sec
    diff_seconds = int(total_seconds(date))

    # is ago or in
    ago_in = 0
    if diff_seconds < 0:
        ago_in = 1  # date is later then now, is the time in future
        diff_seconds *= -1  # chango to positive

    tmp = 0
    i = 0
    while i < SEC_ARRAY_LEN:
        tmp = SEC_ARRAY[i]
        if diff_seconds >= tmp:
            i += 1
            diff_seconds /= tmp
        else:
            break
    diff_seconds = int(diff_seconds)
    i *= 2

    if diff_seconds > (i == 0 and 9 or 1):
        i += 1

    if locale is None:
        locale = DEFAULT_LOCALE

    tmp = timeago_template(locale, i, ago_in)
    if hasattr(tmp, '__call__'):
        tmp = tmp(diff_seconds)
    return '%s' in tmp and tmp % diff_seconds or tmp
599003
def get_date(context, value):
    
    if not value:
        return None
    if isinstance(value, DateTime):
        return value
    if isinstance(value, datetime):
        return dt2DT(value)
    if not isinstance(value, basestring):
        return None

    def try_parse(date_string, format):
        if not format:
            return None
        try:
            struct_time = strptime(date_string, format)
            return datetime(*struct_time[:6])
        except ValueError:
            pass
        return None

    def get_locale_format(key, context):
        format = context.translate(key, domain="senaite.core", mapping={})
        # TODO: Is this replacement below strictly necessary?
        return format.replace(r"${", '%').replace('}', '')

    # Try with prioritized formats
    formats = [get_locale_format("date_format_long", context),
               get_locale_format("date_format_short", context),
               "%Y-%m-%d %H:%M", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S"]
    for pri_format in formats:
        val = try_parse(value, pri_format)
        if not val:
            continue
        val = dt2DT(val)
        if val.timezoneNaive():
            # Use local timezone for tz naive strings
            # see http://dev.plone.org/plone/ticket/10141
            zone = val.localZone(safelocaltime(val.timeTime()))
            parts = val.parts()[:-1] + (zone,)
            val = DateTime(*parts)
        return val

    logger.warn("Unable to convert {} to datetime".format(value))
    return None
498646
def yesterday(self) -> datetime:
        
        self.value = datetime.today() - timedelta(days=1)
        return self.value
1203908
def date_cast(date):
    '''
    
    '''
    if date is None:
        return datetime.datetime.now()
    elif isinstance(date, datetime.datetime):
        return date

    # fuzzy date
    try:
        if isinstance(date, six.string_types):
            try:
                if HAS_TIMELIB:
                    # py3: yes, timelib.strtodatetime wants bytes, not str :/
                    return timelib.strtodatetime(
                        salt.utils.stringutils.to_bytes(date))
            except ValueError:
                pass

            # not parsed yet, obviously a timestamp?
            if date.isdigit():
                date = int(date)
            else:
                date = float(date)

        return datetime.datetime.fromtimestamp(date)
    except Exception:
        if HAS_TIMELIB:
            raise ValueError('Unable to parse {0}'.format(date))

        raise RuntimeError(
                'Unable to parse {0}. Consider installing timelib'.format(date))
932214
def get_cgi_parameter_datetime(form: cgi.FieldStorage,
                               key: str) -> Optional[datetime.datetime]:
    
    try:
        s = get_cgi_parameter_str(form, key)
        if not s:
            # if you dateutil.parser.parse() an empty string,
            # you get today's date
            return None
        d = dateutil.parser.parse(s)
        if d.tzinfo is None:  # as it will be
            d = d.replace(tzinfo=dateutil.tz.tzlocal())
        return d
    except ValueError:
        return None
131800
def _decode_datetime(obj):
    """"""

    if '__datetime__' in obj:
        obj = datetime.datetime.strptime(obj['as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
    return obj
538323
def get_now():
    
    if not get_current_request:
        return datetime.datetime.now()
    request = get_current_request()
    if request:
        openinghours_now = request.GET.get('openinghours-now')
        if openinghours_now:
            return datetime.datetime.strptime(openinghours_now, '%Y%m%d%H%M%S')
    return datetime.datetime.now()
296817
def check_time_param(t):
    """"""

    if type(t) is str:
        if not ISO.match(t):
            raise ValueError('Date string "%s" does not match ISO8601 format' %
                             (t))
        return t
    else:
        return t.isoformat()
685170
def TAF_datetime_to_datetime_object(
    datetime_string             = None,
    datetime_for_year_and_month = None  # e.g. datetime.datetime.utcnow()
    ):

    

    if datetime_string.endswith("24"):

        datetime_string = datetime_string[:-2] + "00"

        tmp = datetime.datetime.strptime(datetime_string, "%d%H") +\
              datetime.timedelta(days = 1)

    else:

        tmp = datetime.datetime.strptime(datetime_string, "%d%H")

    return datetime.datetime(
        datetime_for_year_and_month.year,
        datetime_for_year_and_month.month,
        tmp.day,
        tmp.hour,
        tmp.minute
    )
433877
def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime:
    
    try:
        t = dateutil_parse(v, default=datetime(2000, 1, 1))
        if tz is None:
            tz = pytz.utc
        return t if t.tzinfo else tz.localize(t)
    except Exception:
        if exceptions:
            raise ValidationError('Failed to parse datetime from "{}"'.format(v))
        return default