datetime获取星期方法

主要使用三个方法:

  • weekday()
  • isoweekday()
  • isocalendar()
    import datetime

    time_str = '2021-11-26'
    d = datetime.datetime.strptime(time_str, "%Y-%m-%d")
    print("weekday:\t", d.weekday())
    print("isoweekday:\t", d.isoweekday())
    print("isocalendar:\t", d.isocalendar())
image.png

weekday对应0-6,isoweekday对应1-7,isocalendar返回数组:年,周号,与isoweekday同样的星期范围。

weekday转换小函数
    import datetime

    def get_weekday(date):
        iso_weekday = {
            1: '周一',
            2: '周二',
            3: '周三',
            4: '周四',
            5: '周五',
            6: '周六',
            7: '周日',
        }
        return iso_weekday[date.isoweekday()]

    time_str = '2021-11-26'
    d = datetime.datetime.strptime(time_str, "%Y-%m-%d")
    print(get_weekday(d))

你可能感兴趣的:(datetime获取星期方法)