Output:
2021-05-10 12:59:14.867969 复制代码 比较两个日期 import datetime a = datetime.datetime(2020, 12, 31, 23, 59, 59) b = datetime.datetime(2020, 11, 30, 23, 59, 59) print(a < b) print(a > b) 复制代码Output:
False True 复制代码 从 datetime 对象中提取年份 import datetime year = datetime.date.today().year print(year) 复制代码Output:
2021 复制代码 在 Python 中找到星期几 import pendulum dt = pendulum.parse(\'2021-05-18\') print(dt.day_of_week) dt = pendulum.parse(\'2021-05-01\') print(dt.day_of_week) dt = pendulum.parse(\'2021-05-21\') print(dt.day_of_week) 复制代码Output:
2 6 5 复制代码 从当前日期获取 7 天前的日期 from datetime import datetime, timedelta now = datetime.now() for x in range(7): d = now - timedelta(days=x) print(d.strftime("%Y-%m-%d")) 复制代码Output:
2021-05-18 2021-05-17 2021-05-16 2021-05-15 2021-05-14 2021-05-13 2021-05-12 复制代码 将两个日期时间对象之间的差值转换为秒 import datetime time1 = datetime.datetime.strptime(\'19 01 2021\', \'%d %m %Y\') time2 = datetime.datetime.strptime(\'25 01 2021\', \'%d %m %Y\') difference = time2 - time1 print(difference) seconds = difference.total_seconds() print(seconds) 复制代码Output:
6 days, 0:00:00 518400.0 复制代码 获得任何一个月的第三个星期五 import calendar c = calendar.Calendar(firstweekday=calendar.SUNDAY) year = 2021 month = 5 monthcal = c.monthdatescalendar(year, month) try: third_friday = [day for week in monthcal for day in week if day.weekday() == calendar.FRIDAY and day.month == month][2] print(third_friday) except IndexError: print(\'No date found\') 复制代码Output:
2021-05-21 复制代码 从 Python 中的周数获取日期 import datetime from dateutil.relativedelta import relativedelta week = 25 year = 2021 date = datetime.date(year, 1, 1) + relativedelta(weeks=+week) print(date) 复制代码Output:
2021-06-25 复制代码 获取特定日期的工作日 import datetime print(datetime.date(2020, 5, 15).isocalendar()[2]) 复制代码Output:
5 复制代码 创建一个 15 分钟前的 DateTime import datetime dt = datetime.datetime.now() - datetime.timedelta(minutes=15) print(dt) 复制代码Output:
2021-05-15 22:25:55.897365 复制代码 从特定日期获取周的开始和结束日期 import pendulum dt = pendulum.datetime(2012, 9, 5) start = dt.start_of(\'week\') print(start.to_datetime_string()) end = dt.end_of(\'week\') print(end.to_datetime_string()) 复制代码Output:
2012-09-03 00:00:00 2012-09-09 23:59:59 复制代码 两个日期之间的差异(以秒为单位) from datetime import datetime fmt = \'%Y-%m-%d %H:%M:%S\' d1 = datetime.strptime(\'2020-01-01 17:31:22\', fmt) d2 = datetime.strptime(\'2020-01-03 17:31:22\', fmt) days_diff = d2 - d1 print(days_diff.days * 24 * 60 * 60) 复制代码Output:
172800 复制代码 以这种格式获取昨天的日期MMDDYY from datetime import date, timedelta yesterday = date.today() - timedelta(days=1) print(yesterday.strftime(\'%m%d%y\')) 复制代码Output:
051421 复制代码 从今天的日期获取上周三 from datetime import date from datetime import timedelta today = date.today() offset = (today.weekday() - 2) % 7 wednesday = today - timedelta(days=offset) print(wednesday) 复制代码