周日历(ISO国际标准)介绍
在线周日历(2022年)
在开发过程中,有些汇总咨询需要以周为单位统计,所以介绍下如何进行相互转换。
from datetime import datetime # 时间转周日历 a = datetime.now().strftime("%Y,%W,%w") print(a) # 2022,28,3 # 周日历转时间 a = datetime.strptime("2022,12,3","%Y,%W,%w") print(a) # 2022-03-23 00:00:00
2021年12月
周数 | 周一 | 周二 | 周三 | 周四 | 周五 | 周六 | 周日 |
---|---|---|---|---|---|---|---|
48 | 1 | 2 | 3 | 4 | 5 | ||
49 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
50 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
51 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
52 | 27 | 28 | 29 | 30 | 31 |
2022年1月
周数 | 周一 | 周二 | 周三 | 周四 | 周五 | 周六 | 周日 |
---|---|---|---|---|---|---|---|
52 | 1 | 2 | |||||
1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
2 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
3 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
4 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
5 | 31 |
from datetime import datetime a = datetime.strptime("2021-12-31", "%Y-%m-%d") print(a.strftime("%Y,%W,%w")) # 2021,52,5 a = datetime.strptime("2022-01-01", "%Y-%m-%d") print(a.strftime("%Y,%W,%w")) # 2022,00,6
datetime类型的时间直接调用 isocalendar 方法
from datetime import datetime def str_to_time(time_str: str) -> datetime: return datetime.strptime(time_str, "%Y-%m-%d") time_list = [ "2021-12-30", "2021-12-31", "2022-01-01", "2022-01-02", "2022-01-03", ] for i in time_list: t = str_to_time(i) iso = t.isocalendar() print(i, " > ", f"{iso.year},{iso.week},{iso.weekday}") # 2021-12-30 > 2021,52,4 # 2021-12-31 > 2021,52,5 # 2022-01-01 > 2021,52,6 # 2022-01-02 > 2021,52,7 # 2022-01-03 > 2022,1,1
from datetime import datetime time_list = ( (2021, 52, 4), (2021, 52, 5), (2021, 52, 6), (2021, 52, 7), (2022, 1, 1), ) for year, week, weekday in time_list: t = datetime.fromisocalendar(year, week, weekday) print(f"{year},{week},{weekday}", " > ", t) # 2021,52,4 > 2021-12-30 00:00:00 # 2021,52,5 > 2021-12-31 00:00:00 # 2021,52,6 > 2022-01-01 00:00:00 # 2021,52,7 > 2022-01-02 00:00:00 # 2022,1,1 > 2022-01-03 00:00:00
from datetime import datetime def datetime_to_isoweek(datetime_: datetime) -> tuple[int, int, int]: """时间转换为iso周日历 Args: datetime_ (datetime): 时间 Returns: tuple[int,int,int]: year,week,weekday """ iso = datetime_.isocalendar() return iso.year, iso.week, iso.weekday def isoweek_to_datetime(isoweek: tuple[int, int, int]) -> datetime: """iso周日历转换为时间 Args: isoweek (tuple[int,int,int]): year,week,weekday Returns: datetime: 时间 """ year, week, weekday = isoweek return datetime.fromisocalendar(year, week, weekday)