Python-根據日期計算周對應的日期
阿新 • • 發佈:2018-12-13
import pandas as pd
import datetime
def state(statedate):
# 週日期對應
# 往前取365天
df = pd.DataFrame([str(d)[:10] for d in pd.date_range(end=statedate, periods=365)],columns=['date'])
# 生成周
df['week'] = df['date'].apply(lambda x: int(datetime.datetime.strptime(x,"%Y-%m-%d").strftime("%W" )))
df['week'] = df['week'].apply(lambda x:'%s%s' % ('week', str(x)))
# 取年月
df['new_date'] = df['date'].apply(lambda x: x[-5:])
# 排序
df = df.sort_values(by=['new_date'],ascending=[True])
# 周開始日期
df_first = df.drop_duplicates(subset=['week'], keep='first')
df_first = df_first. rename(columns={'new_date':'start_date'})
# 周結束日期
df_last = df.drop_duplicates(subset=['week'], keep='last')
df_last = df_last.rename(columns={'new_date':'end_date'})
df_date = pd.merge(df_first[['start_date','week']],df_last[['end_date','week']],on='week')
tt = datetime.datetime. strptime(statedate, '%Y-%m-%d')
this_year = tt.year
df_date['start_date'] = df_date['start_date'].apply(lambda x:'%s-%s' % (str(this_year), str(x)))
df_date['end_date'] = df_date['end_date'].apply(lambda x: '%s-%s' % (str(this_year), str(x)))
return df_date
print(state('2018-12-31'))
start_date week end_date
0 2018-01-01 week1 2018-01-07
1 2018-01-08 week2 2018-01-14
2 2018-01-15 week3 2018-01-21
3 2018-01-22 week4 2018-01-28
4 2018-01-29 week5 2018-02-04
5 2018-02-05 week6 2018-02-11
6 2018-02-12 week7 2018-02-18
7 2018-02-19 week8 2018-02-25
8 2018-02-26 week9 2018-03-04
9 2018-03-05 week10 2018-03-11
10 2018-03-12 week11 2018-03-18
11 2018-03-19 week12 2018-03-25
12 2018-03-26 week13 2018-04-01
13 2018-04-02 week14 2018-04-08
14 2018-04-09 week15 2018-04-15
15 2018-04-16 week16 2018-04-22
16 2018-04-23 week17 2018-04-29
17 2018-04-30 week18 2018-05-06
18 2018-05-07 week19 2018-05-13
19 2018-05-14 week20 2018-05-20
20 2018-05-21 week21 2018-05-27
21 2018-05-28 week22 2018-06-03
22 2018-06-04 week23 2018-06-10
23 2018-06-11 week24 2018-06-17
24 2018-06-18 week25 2018-06-24
25 2018-06-25 week26 2018-07-01
26 2018-07-02 week27 2018-07-08
27 2018-07-09 week28 2018-07-15
28 2018-07-16 week29 2018-07-22
29 2018-07-23 week30 2018-07-29
30 2018-07-30 week31 2018-08-05
31 2018-08-06 week32 2018-08-12
32 2018-08-13 week33 2018-08-19
33 2018-08-20 week34 2018-08-26
34 2018-08-27 week35 2018-09-02
35 2018-09-03 week36 2018-09-09
36 2018-09-10 week37 2018-09-16
37 2018-09-17 week38 2018-09-23
38 2018-09-24 week39 2018-09-30
39 2018-10-01 week40 2018-10-07
40 2018-10-08 week41 2018-10-14
41 2018-10-15 week42 2018-10-21
42 2018-10-22 week43 2018-10-28
43 2018-10-29 week44 2018-11-04
44 2018-11-05 week45 2018-11-11
45 2018-11-12 week46 2018-11-18
46 2018-11-19 week47 2018-11-25
47 2018-11-26 week48 2018-12-02
48 2018-12-03 week49 2018-12-09
49 2018-12-10 week50 2018-12-16
50 2018-12-17 week51 2018-12-23
51 2018-12-24 week52 2018-12-30
52 2018-12-31 week53 2018-12-31