Hive date function to achieve day of week

前端 未结 6 876
無奈伤痛
無奈伤痛 2020-12-16 14:00

I\'m looking for a workaround or hive date functions that gives day of the week ,

Sunday - 1
Monday - 2
Tuesday - 3
Wednesday - 4
Thursday - 5
Friday - 6
Sat         


        
相关标签:
6条回答
  • 2020-12-16 14:18

    From Hive 2.2 there is another possibility:

    hive> select extract(dayofweek FROM your_date) FROM your_table;
    
    0 讨论(0)
  • 2020-12-16 14:19

    select pmod(datediff(your_date,'1900-01-07'),7) + 1 as WeekDay from your_table

    • arbitrary start date picked (1900-01-07)
    • calculates the mod 7 day of week (plus 1 to start at 1 instead of zero)
    0 讨论(0)
  • 2020-12-16 14:31

    Expanding on iggy's answer, here is the query to get the days of the week. Adjust the query to set the first day of the week as necessary.

    SELECT current_date AS `Date`,
           CASE date_format(current_date,'u')
               WHEN 1 THEN 'Mon'
               WHEN 2 THEN 'Tues'
               WHEN 3 THEN 'Wed'
               WHEN 4 THEN 'Thu'
               WHEN 5 THEN 'Fri'
               WHEN 6 THEN 'Sat'
               WHEN 7 THEN 'Sun'
    END AS day_of_week
    
    0 讨论(0)
  • 2020-12-16 14:32

    As I said you need to write a UDF which will accept a string as parameter and return a string. Inside the UDF you need to do these steps:

    1.) Parse the input string using SimpleDateFormat(YYYYMMDD)

    2.) Use the Below code to get the day of week:

    Calendar c = Calendar.getInstance();
    c.setTime(yourDate);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    

    3.) Use this dayOfWeek value in a case statement to get your weekday String and return that string.

    Hope this helps...!!!

    0 讨论(0)
  • 2020-12-16 14:32

    Consider using from_unixtime(your date,'u') - this will return day number of week starting from Monday=1. If your date is not in unixtime format, you can use the following instead:

    from_unixtime(unix_timestamp('20140112','yyyyMMdd'),'u')
    

    see: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for simple date format documentation.

    0 讨论(0)
  • 2020-12-16 14:33

    You can now use date_format (Hive 1.2):

    hive> select date_format('2016-12-01' ,'u');
    OK
    4
    
    0 讨论(0)
提交回复
热议问题