spark日期处理

青旅半醒 2023-07-03 08:13 44阅读 0赞

详情查看:https://www.cnblogs.com/feiyumo/p/8760846.html

以防止文章丢失,搬运!转载自飞末!!!
一、获取当前时间
1.current_date获取当前日期

2018-04-09
2.current_timestamp/now()获取当前时间

2018-04-09 15:20:49.247
二、从日期时间中提取字段
1.year,month,day/dayofmonth,hour,minute,second

Examples:> SELECT day(‘2009-07-30’); 30
2.dayofweek (1 = Sunday, 2 = Monday, …, 7 = Saturday),dayofyear

Examples:> SELECT dayofweek(‘2009-07-30’);   5

Since: 2.3.0
3.weekofyear

weekofyear(date) - Returns the week of the year of the given date. A week is considered to start on a Monday and week 1 is the first week with >3 days.

Examples:> SELECT weekofyear(‘2008-02-20’);   8
6.date_format将时间转化为某种格式的字符串

Examples:> SELECT date_format(‘2016-04-08’, ‘y’);    2016
三、日期时间转换
1.unix_timestamp返回当前时间的unix时间戳

Examples:

  1. > SELECT unix_timestamp();  1476884637
  2. > SELECT unix_timestamp('2016-04-08', 'yyyy-MM-dd');   1460041200

2.from_unixtime将时间戳换算成当前时间,to_unix_timestamp将时间转化为时间戳

Examples:

  1. > SELECT from_unixtime(0, 'yyyy-MM-dd HH:mm:ss');  1970-01-01 00:00:00
  2. >SELECT to_unix_timestamp('2016-04-08', 'yyyy-MM-dd');  
  3. 1460041200

3.to_date/date将字符串转化为日期格式,to_timestamp(Since: 2.2.0)

  1. > SELECT to_date('2009-07-30 04:17:52');  2009-07-30
  2. > SELECT to_date('2016-12-31', 'yyyy-MM-dd');   2016-12-31

SELECT to_timestamp(‘2016-12-31 00:12:00’);   2016-12-31 00:12:00

4.quarter 将1年4等分(range 1 to 4)

Examples:> SELECT quarter(‘2016-08-31’); 3
四、日期、时间计算
1.months_between两个日期之间的月数

months_between(timestamp1, timestamp2) - Returns number of months between timestamp1 and timestamp2.

Examples:> SELECT months_between(‘1997-02-28 10:30:00’, ‘1996-10-30’);  3.94959677

  1. add_months返回日期后n个月后的日期

Examples:> SELECT add_months(‘2016-08-31’, 1);  2016-09-30
3.last_day(date),next_day(start_date, day_of_week)

Examples:

SELECT last_day(‘2009-01-12’);  2009-01-31

SELECT next_day(‘2015-01-14’, ‘TU’);  2015-01-20

4.date_add,date_sub(减)

date_add(start_date, num_days) - Returns the date that is num_days after start_date.

Examples:

SELECT date_add(‘2016-07-30’, 1);  2016-07-31

5.datediff(两个日期间的天数)

datediff(endDate, startDate) - Returns the number of days from startDate to endDate.

Examples:> SELECT datediff(‘2009-07-31’, ‘2009-07-30’); 1

发表评论

表情:
评论列表 (有 0 条评论,44人围观)

还没有评论,来说两句吧...

相关阅读

    相关 js 日期处理

    [js 中日期转换成时间戳][js] js字符串转化时间戳可以使用自带函数 Date(要转化的时间字符串)先转化为Date类型,之后再将Date类型转化为时间戳类型,其中

    相关 Java 日期处理

    【前言】 对于日期的处理既是一个重点又是一个难点。软考之前看马士兵的J2SE视频的时候对于日期的处理这一章没有什么感觉,现在再回过头来看共鸣就会多了点。 【过程】 在小结