1

How can I specify dt.week to use north american week number?

2019 Calendar:

enter image description here

For example: Date -> 01.01.2020 is Week 1 of 2020 / 31.12.2019 is Week 53 of 2019

df['Week'] = df['Induction Date'].dt.week.astype(str).str.zfill(2)

Result:

             SENDER_NAME     Induction Date       InductionPlant   Week
0          b'XXXXXXXXXXXX'     2020-01-03          b'XXXXXXXXXX'     01
8910353    b'XXXXXXXXXXXX'     2019-12-31         b'XXXXXXXXXXX'     01
Jonathan Lam
  • 1,237
  • 3
  • 20
  • 49
  • see if this [converting a pandas date to week number](https://stackoverflow.com/questions/31181295/converting-a-pandas-date-to-week-number) helps. – tidakdiinginkan May 09 '20 at 09:41
  • See if this [helps](https://stackoverflow.com/questions/55889766/pandas-datetime-week-not-as-expected/55890652#55890652) – run-out May 09 '20 at 21:14

2 Answers2

1

You can do this:

df['Date'] = pd.to_datetime(df['Date'])
df['Week'] = df['Date'].dt.strftime('%U').astype(np.int) + 1

Output:

   SENDER_NAME        Induction       Date  InductionPlant  Week
0            0  b'XXXXXXXXXXXX' 2020-01-03   b'XXXXXXXXXX'     1
1      8910353  b'XXXXXXXXXXXX' 2019-12-31  b'XXXXXXXXXXX'    53
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
0

This should do it:

# Add this if "Induction Date" is not yet in pandas datetime format
# df["Induction Date"] = pd.to_datetime(df["Induction Date"])

df['Week'] = df['Induction Date'].dt.to_period('W-SAT').dt.week.astype(str).str.zfill(2)

With .dt.to_period('W-SAT'), you're specifying when a week should end, in this case Saturday.

Result looks like this:

+------------------+--------+
| Induction Date   |   Week |
|------------------+--------|
| 2019-12-27       |     52 |
| 2019-12-28       |     52 |
| 2019-12-29       |     01 |
| 2019-12-30       |     01 |
| 2019-12-31       |     01 |
| 2020-01-01       |     01 |
| 2020-01-02       |     01 |
| 2020-01-03       |     01 |
| 2020-01-04       |     01 |
| 2020-01-05       |     02 |
+------------------+--------+
d_gnz
  • 169
  • 12