如何在hive或python中计算周数?这个星期从星期六到星期五

disho6za  于 2021-06-25  发布在  Hive
关注(0)|答案(2)|浏览(447)

我尝试了以下方法:选择weekofyear(当前时间戳),但它计算从周一到周日的一周。我想从星期六到星期五,基于这一点,它应该填充周数。在Hive里如果我们做不到,用python怎么样。?
在python中,我尝试了:

A = datetime.date(2020, 3, 29).isocalendar()[1]

但这也算上了从周一到周六的一周

agxfikkp

agxfikkp1#

再试试,假设一月一号总是在第一周。

from datetime import date
from calendar

def week_number(ndate, week_start=calendar.MONDAY):
    new_years_day = ndate.replace(month=1, day=1)
    offset = (new_years_day.weekday() - week_start) % 7  # Count back to start of week. Modulo for positive value.
    all_days = (ndate - new_years_day).days + offset  # Days ago week 1 started.

    return (all_days // 7) + 1  # Integer division means we don't have to floor() it. Add 1 for human readable numbers.

print(week_number(date(2020, 1, 1)))  # 1, always
print(week_number(date(2020, 3, 29)))  # 13
print(week_number(date(2020, 3, 29), calendar.SATURDAY))  # 14
print(week_number(date(2020, 3, 27), calendar.SATURDAY))  # 13
jv2fixgn

jv2fixgn2#

import datetime

def week_number(ndate):
    odate = datetime.datetime(ndate.year, 1, 1) 
    spec = odate.weekday()
    alldays =    (ndate - odate).days + spec - 4

    mod = alldays % 7
    days = (alldays - mod) / 7

    if (mod > 0):
        days = days + 1

    return (int)days

print(week_number(datetime.datetime.today()))

相关问题