Formats a date, converting the time to the user timezone if one is specified
353128
def format_datetime(time):
    
    user_time_zone = timezone.get_current_timezone()
    if time.tzinfo is None:
        time = time.replace(tzinfo=pytz.utc)
        user_time_zone = pytz.timezone(getattr(settings, 'USER_TIME_ZONE', 'GMT'))

    time = time.astimezone(user_time_zone)
    return time.strftime("%b %d, %Y %H:%M")
421052
function fixInvalidDate(dateString) {
  if (!dateString) {
    return;
  }

  //Convert invalid dates' timezones to GMT using timezoneMap
  dateString = dateString.replace(/BST?/i, function (match) {
    return timezoneMap[match];
  });

  //Some dates come in as ET, CT etc.. and some don't have the correct offset.
  //Matches /ET/EDT/EST/CT/CDT/CST/MT/MDT/MST/PT/PDT/PST if found at the end of a date string
  var newDateString = dateString.replace(/(E|C|M|P)[DS+]?T$/i, function (match) {
    var firstChar = match.charAt(0);
    return isDaylightSavingsTime() ? (firstChar + 'DT') : (firstChar + 'ST');
  });

  return new Date(newDateString);
}
926481
def timezone(rest):
	

	if ' in ' in rest:
		dstr, tzname = rest.split(' in ', 1)
	else:
		dstr, tzname = rest, 'UTC'

	tzobj = TZINFOS[tzname.strip()]
	dt = dateutil.parser.parse(dstr, tzinfos=TZINFOS)
	if dt.tzinfo is None:
		dt = pytz.UTC.localize(dt)
	res = dt.astimezone(tzobj)
	return '{} {} -> {} {}'.format(
		dt.strftime('%H:%M'), dt.tzname() or dt.strftime('%z'),
		res.strftime('%H:%M'), tzname)
29046
void formatTimeZone_O(StringBuilder b, ZonedDateTime d, int width) {
    int[] tz = getTzComponents(d);
    switch (width) {
      case 1:
        wrapTimeZoneGMT(b, tz[TZNEG] == -1, tz[TZHOURS], tz[TZMINS], true);
        break;
        
      case 4:
        wrapTimeZoneGMT(b, tz[TZNEG] == -1, tz[TZHOURS], tz[TZMINS], false);
        break;
    }
  }
694629
def _FormatDateTime(self, event):
    
    try:
      return timelib.Timestamp.CopyToIsoFormat(
          event.timestamp, timezone=self._output_mediator.timezone,
          raise_error=True)

    except (OverflowError, ValueError) as exception:
      self._ReportEventError(event, (
          'unable to copy timestamp: {0!s} to a human readable date and time '
          'with error: {1!s}. Defaulting to: "0000-00-00T00:00:00"').format(
              event.timestamp, exception))

      return '0000-00-00T00:00:00'
1277162
def T(self):
    "'"
    name = self.timezone and self.timezone.tzname(self.data) or None
    if name is None:
      name = self.format('O')
    return unicode(name)
792144
function datetime(date = new Date(), format) {
  if (date && isString(date)) {
    const dateString = date;
    date = new Date(Date.parse(date));

    if (isNaN(date.getTime()) && !format) {
      format = dateString;
      date = new Date();
    }
  }
  format = format || 'YYYY-MM-DD HH:mm:ss';

  const fn = d => {
    return ('0' + d).slice(-2);
  };

  const d = new Date(date);
  const formats = {
    YYYY: d.getFullYear(),
    MM: fn(d.getMonth() + 1),
    DD: fn(d.getDate()),
    HH: fn(d.getHours()),
    mm: fn(d.getMinutes()),
    ss: fn(d.getSeconds())
  };

  return format.replace(/([a-z])\1+/ig, a => {
    return formats[a] || a;
  });
}
446130
def force_utc(time, name='field', precision=6):
    """"""
    if not isinstance(time, datetime.datetime):
        raise CloudValueError("%s should be of type datetime" % (name,))
    clip = 6 - precision
    timestring = time.isoformat()
    if clip:
        timestring = timestring[:-clip]
    return timestring + "Z"
545676
def date_utc(self) -> datetime:
        """"""
        return datetime.utcfromtimestamp(self._node["date"] if "date" in self._node else self._node["taken_at_timestamp"])
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
1024740
function (timeFormat) {
		var tf = timeFormat.replace(/'.*?'/g, '').toLowerCase(), // removes literals
			isIn = function (f, t) { // does the format contain the token?
					return f.indexOf(t) !== -1 ? true : false;
				};
		return {
				hour: isIn(tf, 'h'),
				minute: isIn(tf, 'm'),
				second: isIn(tf, 's'),
				millisec: isIn(tf, 'l'),
				microsec: isIn(tf, 'c'),
				timezone: isIn(tf, 'z'),
				ampm: isIn(tf, 't') && isIn(timeFormat, 'h'),
				iso8601: isIn(timeFormat, 'Z')
			};
	}
151562
def valid_date(date):
    ""
    # We want something that acts like a datetime. In particular,
    # strings indicate a failure to parse down to an object and ints are
    # nonstandard and ambiguous at best.
    if not hasattr(date, 'tzinfo'):
        return False
    # Relevant RFCs define UTC as 'close enough' to GMT, and the maximum
    # difference between UTC and GMT is often stated to be less than a second.
    if date.tzinfo is None or _total_seconds(date.utcoffset()) < 1.1:
        return True
    return False
976840
def to_localized_time(self, date, **kw):
        
        if date is None:
            return ""
        # default options
        options = {
            "long_format": True,
            "time_only": False,
            "context": api.get_portal(),
            "request": api.get_request(),
            "domain": "senaite.core",
        }
        options.update(kw)
        return ulocalized_time(date, **options)
205745
def offset_to_timezone(offset, now=None):
    
    now = now or datetime.now()

    # JS offsets are flipped, so unflip.
    user_offset = -offset

    # Helper: timezone offset in minutes
    def get_tz_offset(tz):
        try:
            return tz.utcoffset(now).total_seconds() / 60
        except (pytz.NonExistentTimeError, pytz.AmbiguousTimeError):
            return tz.localize(now, is_dst=False).utcoffset().total_seconds() / 60

    # Return the timezone with the minimum difference to the user's offset.
    return min(
        (pytz.timezone(tz_name) for tz_name in get_prioritized_timezones()),
        key=lambda tz: abs(get_tz_offset(tz) - user_offset),
    )
653374
function parseDataToDateTime(parsed, parsedZone, opts, format, text) {
  const { setZone, zone } = opts;
  if (parsed && Object.keys(parsed).length !== 0) {
    const interpretationZone = parsedZone || zone,
      inst = DateTime.fromObject(
        Object.assign(parsed, opts, {
          zone: interpretationZone,
          // setZone is a valid option in the calling methods, but not in fromObject
          setZone: undefined
        })
      );
    return setZone ? inst : inst.setZone(zone);
  } else {
    return DateTime.invalid(
      new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)
    );
  }
}
1010623
def convert_timezone(obj, timezone):
    
    if timezone is None:
        return obj.replace(tzinfo=None)
    return pytz.timezone(timezone).localize(obj)
946990
def to_a
      if_timezone_offset(super) do |o,a|
        a[8] = o.dst?
        a[9] = o.abbreviation
        a
      end
    end