Output:
10:11 PM 复制代码 获得一个月的最后一天 import calendar print(calendar.monthrange(2002, 1)[1]) print(calendar.monthrange(2008, 6)[1]) print(calendar.monthrange(2012, 2)[1]) print(calendar.monthrange(2015, 2)[1]) 复制代码Output:
31 30 29 28 复制代码 从工作日值中获取工作日名称 import calendar print(calendar.day_name[0]) print(calendar.day_name[1]) print(calendar.day_name[2]) print(calendar.day_name[3]) print(calendar.day_name[4]) print(calendar.day_name[5]) print(calendar.day_name[6]) 复制代码Output:
Monday Tuesday Wednesday Thursday Friday Saturday Sunday 复制代码 将 N 小时数添加到当前日期时间 from datetime import datetime, timedelta d = datetime.today() + timedelta(hours=18) print(d) 复制代码Output:
2021-05-16 07:36:08.189948 复制代码 从当前日期获取年、月、日、小时、分钟 import datetime now = datetime.datetime.now() print(now.year, now.month, now.day, now.hour, now.minute, now.second) 复制代码Output:
2021 5 15 14 27 33 复制代码 获取特定月份和年份的最后一个星期日 import calendar month = calendar.monthcalendar(2021, 2) last_sunday = max(month[-1][calendar.SUNDAY], month[-2][calendar.SUNDAY]) print(last_sunday) 复制代码Output:
28 复制代码 查找特定日期的年份中的哪一天 import pendulum dt = pendulum.parse(\'2015-05-18\') print(dt.day_of_year) dt = pendulum.parse(\'2019-12-01\') print(dt.day_of_year) dt = pendulum.parse(\'2018-01-21\') print(dt.day_of_year) 复制代码Output:
138 335 21 复制代码 查找当前日期是工作日还是周末 import datetime weekno = datetime.datetime.today().weekday() if weekno < 5: print("Weekday") else: # 5 Sat, 6 Sun print("Weekend") 复制代码Output:
Weekday 复制代码 组合 datetime.date 和 datetime.time 对象 import datetime d = datetime.datetime.combine(datetime.date(2020, 11, 14), datetime.time(10, 23, 15)) print(d) 复制代码Output:
2020-11-14 10:23:15 复制代码 获得每月的第 5 个星期一 import calendar c = calendar.Calendar(firstweekday=calendar.SUNDAY) year = 2016 month = 2 monthcal = c.monthdatescalendar(year, month) try: fifth_monday = [day for week in monthcal for day in week if day.weekday() == calendar.MONDAY and day.month == month][4] print(fifth_monday) except IndexError: print(\'No date found\') 复制代码Output:
2016-02-29 复制代码 将日期时间对象转换为日期对象 from datetime import datetime datetime_obj = datetime(2020, 12, 15, 10, 15, 45, 321474) print(datetime_obj) date_obj = datetime_obj.date() print(date_obj) 复制代码Output:
2020-12-15 10:15:45.321474 2020-12-15 复制代码 获取没有微秒的当前日期时间 from datetime import datetime print(datetime.now().isoformat(\' \', \'seconds\')) 复制代码Output:
2021-05-15 12:55:45 复制代码 将 N 秒数添加到特定日期时间 import datetime a = datetime.datetime(2020, 12, 31, 23, 59, 45) b = a + datetime.timedelta(seconds=30) print(a) print(b) 复制代码Output:
2020-12-31 23:59:45 2021-01-01 00:00:15 复制代码 从当前日期获取两位数的月份和日期 import datetime dt = datetime.datetime.now() print(dt.strftime(\'%m\')) print(\'{:02d}\'.format(dt.month)) print(f\'{dt.month:02d}\') print(\'%02d\' % dt.month) print(dt.strftime(\'%d\')) print(\'{:02d}\'.format(dt.day)) print(f\'{dt.day:02d}\') print(\'%02d\' % dt.day) 复制代码