2

I have the following table:

Time                     
2016-09-10T23:20:00.000000000
2016-08-10T23:20:00.000000000
2016-09-10T23:20:00.000000000
2017-09-10T23:20:00.000000000
2016-09-10T23:20:00.000000000

I wish to used isocalender to get the work weeks, so any ideas can share me?

Time                               WW
2016-01-01T23:20:00.000000000      201601
2016-01-01T23:20:00.000000000      201601
2016-01-01T23:20:00.000000000      201601
2017-01-01T23:20:00.000000000      201701
2018-01-01T23:20:00.000000000      201801
Shi Jie Tio
  • 2,479
  • 5
  • 24
  • 41

1 Answers1

7

You can use:

#convert column to datetime
df['Time'] = pd.to_datetime(df['Time'])

#simplier solution with strftime
df['WW'] = df['Time'].dt.strftime('%G-%V')
#solution with isocalendar
df['WW1'] = df['Time'].apply(lambda x: str(x.isocalendar()[0]) + '-' + 
                                       str(x.isocalendar()[1]).zfill(2))
print (df)
                 Time       WW      WW1
0 2017-01-01 00:00:00  2016-52  2016-52 <- changed datetime
1 2016-08-10 23:20:00  2016-32  2016-32
2 2016-09-10 23:20:00  2016-36  2016-36
3 2017-09-10 23:20:00  2017-36  2017-36
4 2016-09-10 23:20:00  2016-36  2016-36

Thank you @Fierr for correct '%Y-%V' to '%G-%V'.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • hi, if my weeks is 1, then anyway can have a output like 01? – Shi Jie Tio Jan 02 '18 at 09:53
  • I dont test it, give me a sec. – jezrael Jan 02 '18 at 09:53
  • 1
    You can use `zfill` function like `df['WW1'] = datetimes.apply(lambda x: str(x.isocalendar()[0]) + '-' + str(x.isocalendar()[1]).zfill(2))` – jezrael Jan 02 '18 at 09:54
  • Wouldn't advice to use strftime: seems incorrect to me. Example: print(dt.datetime(2017,1,1).strftime('%Y-%V')). Which gives 2017-52. – Fierr Jan 29 '20 at 11:38
  • @Fierr - Yop, I agree. check [this](https://stackoverflow.com/a/35129654) – jezrael Jan 29 '20 at 11:38
  • 1
    Correction to the above: I do suggest to use strftime, but with the ISO-8601 implementation of YEAR-WEEK, which is '%G-%V' instead of '%Y-%V'. %G is the ISO year equivalent of %Y. – Fierr Jan 29 '20 at 13:08