Skip to content

Commit 84c01bc

Browse files
authored
REF: de-duplicate Period freq conversion code (#31577)
1 parent 918cc48 commit 84c01bc

File tree

1 file changed

+9
-15
lines changed

1 file changed

+9
-15
lines changed

pandas/_libs/tslibs/period.pyx

+9-15
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,8 @@ cdef int64_t DtoB_weekday(int64_t unix_date) nogil:
272272

273273
cdef int64_t DtoB(npy_datetimestruct *dts, int roll_back,
274274
int64_t unix_date) nogil:
275+
# calculate the current week (counting from 1970-01-01) treating
276+
# sunday as last day of a week
275277
cdef:
276278
int day_of_week = dayofweek(dts.year, dts.month, dts.day)
277279

@@ -506,7 +508,11 @@ cdef int64_t asfreq_DTtoM(int64_t ordinal, asfreq_info *af_info) nogil:
506508

507509
cdef int64_t asfreq_DTtoW(int64_t ordinal, asfreq_info *af_info) nogil:
508510
ordinal = downsample_daytime(ordinal, af_info)
509-
return (ordinal + 3 - af_info.to_end) // 7 + 1
511+
return unix_date_to_week(ordinal, af_info.to_end)
512+
513+
514+
cdef int64_t unix_date_to_week(int64_t unix_date, int to_end) nogil:
515+
return (unix_date + 3 - to_end) // 7 + 1
510516

511517

512518
# --------------------------------------------------------------------
@@ -787,22 +793,10 @@ cdef int64_t get_period_ordinal(npy_datetimestruct *dts, int freq) nogil:
787793
return unix_date
788794

789795
elif freq == FR_BUS:
790-
# calculate the current week (counting from 1970-01-01) treating
791-
# sunday as last day of a week
792-
weeks = (unix_date + 3) // 7
793-
# calculate the current weekday (in range 1 .. 7)
794-
delta = (unix_date + 3) % 7 + 1
795-
# return the number of business days in full weeks plus the business
796-
# days in the last - possible partial - week
797-
if delta > 6:
798-
# We have a Sunday, which rolls back to the previous Friday,
799-
# just like Saturday, so decrement delta by 1 to treat as saturday
800-
delta = 6
801-
return (5 * weeks) + delta - 4
796+
return DtoB(dts, 0, unix_date)
802797

803798
elif freq_group == FR_WK:
804-
day_adj = freq - FR_WK
805-
return (unix_date + 3 - day_adj) // 7 + 1
799+
return unix_date_to_week(unix_date, freq - FR_WK)
806800

807801

808802
cdef void get_date_info(int64_t ordinal, int freq,

0 commit comments

Comments
 (0)