Reads the NTP time stamp at the given offset in the buffer and returns
it as a system time (milliseconds since January 1, 1970).
486077
private long readTimeStamp(byte[] buffer, int offset) {
        long seconds = read32(buffer, offset);
        long fraction = read32(buffer, offset + 4);
        return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
    }
67393
@Override
	public Date readDate() {
		/*
		 * Date: 0x0B T7 T6 .. T0 Z1 Z2 T7 to T0 form a 64 bit Big Endian number
		 * that specifies the number of nanoseconds that have passed since
		 * 1/1/1970 0:00 to the specified time. This format is UTC 1970. Z1 an
		 * Z0 for a 16 bit Big Endian number indicating the indicated time's
		 * timezone in minutes.
		 */
		long ms = (long) buf.getDouble();
		// The timezone can be ignored as the date always is encoded in UTC
		@SuppressWarnings("unused")
		short timeZoneMins = buf.getShort();
		Date date = new Date(ms);
		storeReference(date);
		return date;
	}
500691
public static String timestampToString(double timestamp) {
	if (timestamp == 0) return "0";

	// timestamp is relative to 1900, utc is used by Java and is relative
	// to 1970
	double utc = timestamp - (2208988800.0);

	// milliseconds
	long ms = (long) (utc * 1000.0);

	// date/time
	String date = DateFormatPool.format("dd-MMM-yyyy HH:mm:ss", new Date(ms));

	// fraction
	double fraction = timestamp - ((long) timestamp);
	String fractionSting = new DecimalFormat(".000000").format(fraction);

	return date + fractionSting;
    }
1122674
def utcoffset(self, dt):
        """"""
        tt = _localtime(_mktime((dt.year, dt.month, dt.day,
                 dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
        if tt.tm_isdst > 0: return _dstoffset
        return _stdoffset
454187
def _dtfromtimestamp(timestamp):
    
    try:
        return datetime.datetime.fromtimestamp(timestamp)
    except OSError:
        timestamp -= time.timezone
        dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
        if _isdst(dt):
            timestamp += 3600
            dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
        return dt
1287352
def utcfromtimestamp(cls, t):
        ""
        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us)
996437
public byte[] getData(byte[] dst, int offset)
	{
		final int end = Math.min(data.length, dst.length - offset) / 3 * 3;
		for (int i = 0; i < end; ++i)
			dst[offset + i] = (byte) data[i];
		return dst;
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
	 */
	public Map getSubTypes()
	{
		return types;
	}

	/**
	 * @return the subtypes of the date translator type
	 * @see DPTXlator#getSubTypesStatic()
	 */
	protected static Map getSubTypesStatic()
	{
		return types;
	}

	private String fromDPT(int index)
	{
		if (sdf != null)
			synchronized (DPTXlatorDate.class) {
				try {
					return sdf.format(new Date(fromDPTMillis(index)));
				}
				catch (final KNXFormatException e) {}
				return "invalid date";
			}
		final int i = index * 3;
		// return year-month-day
		final int d = data[i + DAY];
		final int m = data[i + MONTH];
		return Short.toString(absYear(data[i + YEAR])) + '-' + align(m) + m + '-'
			+ align(d) + d;
	}

	private long fromDPTMillis(int index) throws KNXFormatException
	{
		synchronized (DPTXlatorDate.class) {
			getCalendar().clear();
			final int i = index * 3;
			c.set(Calendar.DAY_OF_MONTH, data[i + DAY]);
			c.set(Calendar.MONTH, data[i + MONTH] - 1);
			c.set(Calendar.YEAR, absYear(data[i + YEAR]));
			try {
				return c.getTimeInMillis();
			}
			catch (final IllegalArgumentException e) {
				throw new KNXFormatException(e.getMessage());
			}
		}
	}

	protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
	{
		if (sdf != null)
			synchronized (DPTXlatorDate.class) {
				toDPT(parse(value), dst, index);
				return;
			}
		final StringTokenizer t = new StringTokenizer(value, "- ");
		final int maxTokens = 3;
		final int[] tokens = new int[maxTokens];
		try {
			int count = 0;
			for (; count < maxTokens && t.hasMoreTokens(); ++count)
				tokens[count] = Short.parseShort(t.nextToken());
			if (count < 3)
				throw logThrow(LogLevel.WARN, "invalid date " + value, null, value);
			set(tokens[0], tokens[1], tokens[2], dst, index);
		}
		catch (final KNXIllegalArgumentException e) {
			throw logThrow(LogLevel.WARN, "invalid date " + value, e.getMessage(), value);
		}
		catch (final NumberFormatException e) {
			throw logThrow(LogLevel.WARN, "invalid number in " + value, null, value);
		}
	}

	private short[] toDPT(long milliseconds, short[] dst, int index)
	{
		synchronized (DPTXlatorDate.class) {
			getCalendar().clear();
			c.setTimeInMillis(milliseconds);
			set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c
				.get(Calendar.DAY_OF_MONTH), dst, index);
		}
		return dst;
	}

	private short[] set(int year, int month, int day, short[] dst, int index)
	{
		if (year < 1990 || year > 2089)
			throw new KNXIllegalArgumentException("year out of range [1990..2089]");
		if (month < 1 || month > 12)
			throw new KNXIllegalArgumentException("month out of range [1..12]");
		if (day < 1 || day > 31)
			throw new KNXIllegalArgumentException("day out of range [1..31]");
		final int i = 3 * index;
		dst[i + DAY] = (short) day;
		dst[i + MONTH] = (short) month;
		dst[i + YEAR] = (short) (year % 100);
		return dst;
	}

	private short absYear(int relative)
	{
		if (relative > 99)
			throw new KNXIllegalArgumentException("relative year out of range [0..99]");
		return (short) (relative + (relative < 90 ? 2000 : 1900));
	}

	private long parse(String value) throws KNXFormatException
	{
		try {
			return sdf.parse(value).getTime();
		}
		catch (final ParseException e) {
			throw logThrow(LogLevel.WARN, "invalid date format", e.getMessage(), value);
		}
	}

	private static String align(int number)
	{
		return number > 9 ? "" : "0";
	}

	private static Calendar getCalendar()
	{
		// don't need to synchronize, it's harmless if we have 2 instances
		// and we synchronize on class anyway
		if (c == null) {
			final Calendar calendar = Calendar.getInstance();
			calendar.setLenient(false);
			c = calendar;
		}
		return c;
	}
}
1332029
def pkt2uptime(pkt, HZ=100):
    """"""
    if not isinstance(pkt, Packet):
        raise TypeError("Not a TCP packet")
    if isinstance(pkt, NoPayload):
        raise TypeError("Not a TCP packet")
    if not isinstance(pkt, TCP):
        return pkt2uptime(pkt.payload)
    for opt in pkt.options:
        if opt[0] == "Timestamp":
            # t = pkt.time - opt[1][0] * 1.0/HZ
            # return time.ctime(t)
            t = opt[1][0] / HZ
            return t
    raise TypeError("No timestamp option")
895620
public static final long read(ReadableByteChannel channel, ByteBuffer[] dsts, int offset, int length) throws IOException
    {
        long res = 0;
        for  (int ii=0;ii<length;ii++)
        {
            ByteBuffer bb = dsts[ii+offset];
            if (bb.hasRemaining())
            {
                int rc = channel.read(bb);
                if (rc == -1)
                {
                    if (res == 0)
                    {
                        return -1;
                    }
                    else
                    {
                        return res;
                    }
                }
                res += rc;
                if (bb.hasRemaining())
                {
                    break;
                }
            }
        }
        return res;
    }
558431
static public Timestamp adjustTimestamp(Timestamp timestamp)
  {
    long milliToAdjust = ResultUtil.msDiffJulianToGregorian(timestamp);

    if (milliToAdjust != 0)
    {

      if (logger.isDebugEnabled())
      {
        logger.debug("adjust timestamp by {} days", milliToAdjust / 86400000);
      }

      Timestamp newTimestamp = new Timestamp(timestamp.getTime()
                                             + milliToAdjust);

      newTimestamp.setNanos(timestamp.getNanos());

      return newTimestamp;
    }
    else
    {
      return timestamp;
    }
  }
777978
def timestamp(s):
    '''
    
    '''
    ms_s = s[6:]
    ms = ms_s and int(float(ms_s) * 1000000) or 0

    t = datetime.time(
        hour=int(s[0:2]),
        minute=int(s[2:4]),
        second=int(s[4:6]),
        microsecond=ms)
    return t
818497
def get_offset(target):
    
    from pytz import timezone
    import pytz
    from datetime import datetime

    utc = pytz.utc

    today = datetime.now()
    tz_target = timezone(tf.certain_timezone_at(lat=target['lat'], lng=target['lng']))
    # ATTENTION: tz_target could be None! handle error case
    today_target = tz_target.localize(today)
    today_utc = utc.localize(today)
    return (today_utc - today_target).total_seconds() / 60
1247745
def get_packet_time(self, pkt):
        """"""
        if pkt.sent_time:
          t = pkt.sent_time
          sec = int(t)
        else:
          t = pkt.time
          sec = int(t)
        usec = int(round((t-sec)*1000000))
        return (sec,usec)
1267537
public static double decodeTimestamp(byte[] array, int pointer) {
	double r = 0.0;

	for (int i = 0; i < 8; i++) {
	    r += unsignedByteToShort(array[pointer + i]) * Math.pow(2, (3 - i) * 8);
	}

	return r;
    }
15693
public void toBinDate(TimeZone tz, byte[] bytes, Date value) throws PSQLException {
    long millis = value.getTime();

    if (tz == null) {
      tz = getDefaultTz();
    }
    // It "getOffset" is UNTESTED
    // See org.postgresql.jdbc.AbstractJdbc2Statement.setDate(int, java.sql.Date,
    // java.util.Calendar)
    // The problem is we typically do not know for sure what is the exact required date/timestamp
    // type
    // Thus pgjdbc sticks to text transfer.
    millis += tz.getOffset(millis);

    long secs = toPgSecs(millis / 1000);
    ByteConverter.int4(bytes, 0, (int) (secs / 86400));
  }
323025
public long getOffset() throws IOException {
	/// Send request
	DatagramSocket socket = null;
	try {
	    socket = new DatagramSocket();
	    socket.setSoTimeout(20000);
	    InetAddress address = InetAddress.getByName(serverName);
	    byte[] buf = new NtpMessage().toByteArray();
	    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 123);

	    // Set the transmit timestamp *just* before sending the packet
	    NtpMessage.encodeTimestamp(packet.getData(), 40, (System.currentTimeMillis() / 1000.0) + 2208988800.0);

	    socket.send(packet);

	    // Get response
	    packet = new DatagramPacket(buf, buf.length);
	    socket.receive(packet);

	    // Immediately record the incoming timestamp
	    double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;

	    // Process response
	    NtpMessage msg = new NtpMessage(packet.getData());
	    // double roundTripDelay = (destinationTimestamp-msg.originateTimestamp) -
	    // (msg.receiveTimestamp-msg.transmitTimestamp);
	    double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;

	    return (long) (localClockOffset * 1000);
	}
	finally {
	    IOUtil.closeEL(socket);
	}
    }
93613
def tai_timestamp():
    """"""
    timestamp = time.time()
    date = datetime.utcfromtimestamp(timestamp)
    if date.year < 1972:
        return timestamp
    offset = 10 + timestamp
    leap_seconds = [
        (1972, 1, 1),
        (1972, 7, 1),
        (1973, 1, 1),
        (1974, 1, 1),
        (1975, 1, 1),
        (1976, 1, 1),
        (1977, 1, 1),
        (1978, 1, 1),
        (1979, 1, 1),
        (1980, 1, 1),
        (1981, 7, 1),
        (1982, 7, 1),
        (1983, 7, 1),
        (1985, 7, 1),
        (1988, 1, 1),
        (1990, 1, 1),
        (1991, 1, 1),
        (1992, 7, 1),
        (1993, 7, 1),
        (1994, 7, 1),
        (1996, 1, 1),
        (1997, 7, 1),
        (1999, 1, 1),
        (2006, 1, 1),
        (2009, 1, 1),
        (2012, 7, 1),
        (2015, 7, 1),
        (2017, 1, 1),
    ]
    for idx, leap_date in enumerate(leap_seconds):
        if leap_date >= (date.year, date.month, date.day):
            return idx - 1 + offset
    return len(leap_seconds) - 1 + offset