Jolly23
V2EX  ›  问与答

通过 python,如何给定一个周数和星期,算出日期?

  •  
  •   Jolly23 · Jul 24, 2016 · 5487 views
    This topic created in 3756 days ago, the information mentioned may be changed or developed.

    如题: 怎么样才能提供一个 周数(全年当中的第几周)和星期,来计算出这个日期(年月日)

    7 replies  •  2016-07-24 13:25:37 +08:00
    cyr1l
    cyr1l
    Jul 24, 2016 via iPhone
    2
    年是已知的吧?你只需要求月日。
    Jolly23
    Jolly23
    OP
    Jul 24, 2016
    3
    @cyr1l 是的
    SuperMild
    SuperMild
    Jul 24, 2016
    4
    - 用闰年公式算出是否闰年,这样每个月有多少天就确定了

    - 使用计算星期几的公式(例如蔡勒公式, w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1 )计算出当年 1 月 1 日是星期几

    - 利用上述两个数据推算即可
    sunus
    sunus
    Jul 24, 2016
    5
    可以用 isoweek 这个库 https://pypi.python.org/pypi/isoweek/
    crazykuma
    crazykuma
    Jul 24, 2016
    6
    pandas 的 dateoffset 就可以做到

    from pandas.tseries.offsets import *
    d=datetime(2016,1,1)
    d+Week(2,weekday=0) #2 周后的星期一
    Jolly23
    Jolly23
    OP
    Jul 24, 2016
    7
    做完了,感谢大家的帮助 @sunus @crazykuma @SuperMild @cyr1l @hahastudio

    def iso_to_gregorian(iso_year, iso_week, iso_day):
    fourth_jan = date(iso_year, 1, 4)
    delta = timedelta(fourth_jan.isoweekday() - 1)
    iso_year_start = fourth_jan - delta
    year_start = iso_year_start
    return year_start + timedelta(days=iso_day-1, weeks=iso_week-1)


    def iso_to_date(iso_year, iso_week, iso_day):
    return iso_to_gregorian(iso_year, iso_week, iso_day).strftime("%Y-%m-%d")

    print iso_to_date(2016, 30, 3)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1558 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 23:39 · PVG 07:39 · LAX 15:39 · JFK 18:39
    ♥ Do have faith in what you're doing.