Tries to convert any type of argument to datetime

    Args:
        arg: datetime, date, or str. If "?", will be converted to 1970-1-1.
             if 0 or "now", will be converted to datetime.datetime.now()
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
651472
def parse_datetime(val, fmt=None):
  
  if isinstance(val, datetime):
    return val
  else:
    return _parse_datetime(_normalize_tz(str(val)), fmt)
773988
def to_date(value, default=None):
    
    if isinstance(value, DateTime):
        return value
    if not value:
        if default is None:
            return None
        return to_date(default)
    try:
        if isinstance(value, str) and '.' in value:
            # https://docs.plone.org/develop/plone/misc/datetime.html#datetime-problems-and-pitfalls
            return DateTime(value, datefmt='international')
        return DateTime(value)
    except:
        return to_date(default)
741785
def touch(args):
    
    from time import ctime

    p = OptionParser(touch.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    info, = args
    fp = open(info)
    for row in fp:
        path, atime, mtime = row.split()
        atime = float(atime)
        mtime = float(mtime)
        current_atime, current_mtime = get_times(path)

        # Check if the time has changed, with resolution up to 1 sec
        if int(atime) == int(current_atime) and \
           int(mtime) == int(current_mtime):
            continue

        times = [ctime(x) for x in (current_atime, current_mtime, atime, mtime)]
        msg = "{0} : ".format(path)
        msg += "({0}, {1}) => ({2}, {3})".format(*times)
        print(msg, file=sys.stderr)
        os.utime(path, (atime, mtime))
899987
def convert_date(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, datetime.date):
        return value
    for fmt in settings.DATE_INPUT_FORMATS:
        try:
            return datetime.datetime.strptime(value, fmt).date()
        except (ValueError, TypeError):
            continue
    raise ValueError("`{}` does not match a format in settings.DATE_INPUT_FORMATS".format(value))
475492
def run
      if parsed_options? && arguments_valid?
        puts "Start at #{DateTime.now}\n\n" if @options.verbose

        output_options if @options.verbose # [Optional]

        process_arguments
        process_command

        puts "\nFinished at #{DateTime.now}" if @options.verbose

      else
        puts "ERROR: Invalid Options passed. Please run with --help"
        exit 1
      end

    end
290349
def current_time(self, date):
        
        ret = self.command(
            'global.cgi?action=setCurrentTime&time={0}'.format(date)
        )

        if "ok" in ret.content.decode('utf-8').lower():
            return True

        return False
1298021
def time_ago_to_date(value):
    
    today = datetime.date.today()

    if value == 'today':
        return today
    elif value == 'yesterday':
        return today - datetime.timedelta(days=1)

    time_ago = re.match(r'(\d+) (days?|weeks?|months?|years?) ago', value)

    if time_ago:
        duration, unit = int(time_ago.group(1)), time_ago.group(2)

        if 'day' in unit:
            return today - datetime.timedelta(days=duration)
        elif 'week' in unit:
            return today - datetime.timedelta(weeks=duration)
        elif 'month' in unit:
            return months_ago(today, duration)
        elif 'year' in unit:
            return today.replace(year=today.year - duration)

    return datetime.datetime.strptime(value, '%d.%m.%Y').date()
162121
def to_date(value, default=None):
    
    if isinstance(value, DateTime):
        return value
    if not value:
        if default is None:
            return None
        return to_date(default)
    try:
        if isinstance(value, str) and '.' in value:
            # https://docs.plone.org/develop/plone/misc/datetime.html#datetime-problems-and-pitfalls
            return DateTime(value, datefmt='international')
        return DateTime(value)
    except (TypeError, ValueError, DateTimeError):
        return to_date(default)
653701
def to_datetime(value, ctx):
    
    if isinstance(value, str):
        temporal = ctx.get_date_parser().auto(value)
        if temporal is not None:
            return to_datetime(temporal, ctx)
    elif type(value) == datetime.date:
        return ctx.timezone.localize(datetime.datetime.combine(value, datetime.time(0, 0)))
    elif isinstance(value, datetime.datetime):
        return value.astimezone(ctx.timezone)

    raise EvaluationError("Can't convert '%s' to a datetime" % str(value))
499328
def chk_date_arg(s):
    """"""
    if re_date.search(s) is None:
        return False
    comp = s.split('-')
    try:
        dt = datetime.date(int(comp[0]), int(comp[1]), int(comp[2]))
        return True
    except Exception as e:
        return False
352506
def convert_datetime(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, datetime.datetime):
        return value
    for fmt in settings.DATETIME_INPUT_FORMATS:
        try:
            return datetime.datetime.strptime(value, fmt)
        except (ValueError, TypeError):
            continue
    raise ValueError("`{}` does not match a format in settings.DATETIME_INPUT_FORMATS".format(value))
958272
def update_datetime(value, range = None):
        
        range = range if range != None else 10
        if range < 0:
            return value
        
        days = RandomFloat.next_float(-range, range)

        return value + datetime.timedelta(days)
249620
public static function TimezoneFromDateTime( $arg )
	{
		if ( $arg instanceof Undefined )
		{
			return Undefined::getValue();
		}

		if ( ! $arg instanceof DateTimeValue )
		{
			return Undefined::getValue();
		}

		/**
		 * @var DateTimeValue $dateTime
		 */
		$dateTime = $arg;

		if ( $dateTime->IsLocal )
			return Undefined::getValue();

		return $dateTime->TimezoneToInterval();
	}
52684
def _validate_date_str(str_):
    """"""

    if not str_:
        return None

    # Convert to datetime so we can validate it's a real date that exists then
    # convert it back to the string.
    try:
        date = datetime.strptime(str_, DATE_FMT)
    except ValueError:
        msg = 'Invalid date format, should be YYYY-MM-DD'
        raise argparse.ArgumentTypeError(msg)

    return date.strftime(DATE_FMT)
588492
public static function AdjustDateToTimezone( $arg )
	{
		if ( $arg instanceof Undefined )
			return Undefined::getValue();

		/**
		 * @var DateValue $date
		 */
		$date = $arg;
		if ( $date->IsLocal ) return $date;

		$dt = clone $date->Value;
		$dtz = new \DateTimeZone( date_default_timezone_get() );
		$dt->setTimezone( $dtz );
		$dateTime = DateValue::fromDate( $date->S,  $dt, false );
		$dateTime->IsLocal = false;
		return $dateTime;

	}
31712
def today(self) -> datetime:
        
        self.value = datetime.combine(datetime.today().date(), time.min)
        return self.value