Извлечь дату из unix_timestamp, которая находится в строчном формате Apache Spark? [Дубликат]

Math.sum (javascript) .... вид замещения оператора

.1 + .0001 + -.1 --> 0.00010000000000000286
Math.sum(.1 , .0001, -.1) --> 0.0001

Object.defineProperties(Math, {
    sign: {
        value: function (x) {
            return x ? x < 0 ? -1 : 1 : 0;
            }
        },
    precision: {
        value: function (value, precision, type) {
            var v = parseFloat(value), 
                p = Math.max(precision, 0) || 0, 
                t = type || 'round';
            return (Math[t](v * Math.pow(10, p)) / Math.pow(10, p)).toFixed(p);
        }
    },
    scientific_to_num: {  // this is from https://gist.github.com/jiggzson
        value: function (num) {
            //if the number is in scientific notation remove it
            if (/e/i.test(num)) {
                var zero = '0',
                        parts = String(num).toLowerCase().split('e'), //split into coeff and exponent
                        e = parts.pop(), //store the exponential part
                        l = Math.abs(e), //get the number of zeros
                        sign = e / l,
                        coeff_array = parts[0].split('.');
                if (sign === -1) {
                    num = zero + '.' + new Array(l).join(zero) + coeff_array.join('');
                } else {
                    var dec = coeff_array[1];
                    if (dec)
                        l = l - dec.length;
                    num = coeff_array.join('') + new Array(l + 1).join(zero);
                }
            }
            return num;
         }
     }
    get_precision: {
        value: function (number) {
            var arr = Math.scientific_to_num((number + "")).split(".");
            return arr[1] ? arr[1].length : 0;
        }
    },
    diff:{
        value: function(A,B){
            var prec = this.max(this.get_precision(A),this.get_precision(B));
            return +this.precision(A-B,prec);
        }
    },
    sum: {
        value: function () {
            var prec = 0, sum = 0;
            for (var i = 0; i < arguments.length; i++) {
                prec = this.max(prec, this.get_precision(arguments[i]));
                sum += +arguments[i]; // force float to convert strings to number
            }
            return Math.precision(sum, prec);
        }
    }
});

Идея состоит в том, чтобы вместо Math вместо Math использовать ошибки плавания

Math.diff(0.2, 0.11) == 0.09 // true
0.2 - 0.11 == 0.09 // false

также отмечают, что Math.diff и Math.sum автоматически определяют точность использования

. Math.sum принимает любое количество аргументов

17
задан Hammad Haleem 9 March 2016 в 05:29
поделиться

5 ответов

Я решил эту проблему, используя библиотеку joda-time , путем сопоставления на DataFrame и преобразования DateTime в строку:

import org.joda.time._
val time_col = sqlContext.sql("select ts from mr")
                         .map(line => new DateTime(line(0)).toString("yyyy-MM-dd"))
6
ответ дан eliasah 27 August 2018 в 23:59
поделиться

Здесь используются функции Scala DataFrame: from_unix_time и to_date

// NOTE: divide by 1000 required if milliseconds
// e.g. 1446846655609 -> 2015-11-06 21:50:55 -> 2015-11-06 
mr.select(to_date(from_unixtime($"ts" / 1000))) 
11
ответ дан Gevorg 27 August 2018 в 23:59
поделиться
import org.joda.time.{DateTimeZone}
import org.joda.time.format.DateTimeFormat

Вам нужно импортировать следующие библиотеки.

val stri = new DateTime(timeInMillisec).toDateTime.toString("yyyy/MM/dd")

Или настроить на ваш случай:

 val time_col = sqlContext.sql("select ts from mr")
                     .map(line => new DateTime(line(0).toInt).toDateTime.toString("yyyy/MM/dd"))

Может быть другой способ:

  import com.github.nscala_time.time.Imports._

  val date = (new DateTime() + ((threshold.toDouble)/1000).toInt.seconds )
             .toString("yyyy/MM/dd")

Надеюсь, это поможет:)

11
ответ дан Hammad Haleem 27 August 2018 в 23:59
поделиться

Вам не нужно преобразовывать в String перед применением toDataTime с помощью nscala_time

import com.github.nscala_time.time.Imports._

scala> 1435655706000L.toDateTime
res4: org.joda.time.DateTime = 2015-06-30T09:15:06.000Z

`

5
ответ дан Orar 27 August 2018 в 23:59
поделиться

Начиная с искры 1.5, для этого есть встроенный UDF.

val df = sqlContext.sql("select from_unixtime(ts,'YYYY-MM-dd') as `ts` from mr")

Для получения дополнительной информации проверьте Spark 1.5.2 API Doc .

20
ответ дан Yuan Zhao 27 August 2018 в 23:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: