dateutil
为 Python 标准库 datetime
提供了强大的扩展
功能:
pip install python-dateutil
from dateutil.parser import parse
from dateutil.easter import easter
from dateutil.rrule import rrule, YEARLY, FR
from dateutil.relativedelta import relativedelta
now = parse('May 20 13:14:00 UTC 2020') # UTC为世界统一时间
today = now.date() # 转换为日期
year = rrule(YEARLY, dtstart=now, bymonth=8, bymonthday=13, byweekday=FR)[0].year
rdelta = relativedelta(easter(year), today)
print('这一天是: {}'.format(today))
print('下一个8.13为周五在 {} 年'.format(year))
print('那一年的复活节离现在有多远: {}'.format(rdelta))
print('那一年的复活节日期: {}'.format(today + rdelta))
# 今天是: 2020-05-20
# 下一个8.13为周五在 2021 年
# 那一年的复活节离现在有多远: relativedelta(months=+10, days=+15)
# 那一年的复活节日期: 2021-04-04
from dateutil.parser import parse
print(parse('2022-09-06') > parse('2022-09-05')) # True
print(parse('2022-09-06 10:00:00') > parse('2022-09-05 00:00:00')) # True
使用 dateutil.relativedelta
类初始化设置的参数,并进行 + 操作
相对时间:years, months, days 等,带 s 结尾
绝对时间:year, month, day 等
import calendar
from datetime import date, datetime
from dateutil.relativedelta import *
NOW = datetime.now()
TODAY = date.today()
print('现在时间', NOW)
print('今天日期', TODAY)
print('下个月', NOW + relativedelta(months=+1)) # 注意参数有s
print('下个月再加一周', NOW + relativedelta(months=+1, weeks=+1))
print('下个月再加一周的早上10点', TODAY + relativedelta(months=+1, weeks=+1, hour=10)) # 注意用的是日期,且hour没s
print('一年前一个月', NOW + relativedelta(years=+1, months=-1))
print('下周五', TODAY + relativedelta(weekday=FR))
print('下周五', TODAY + relativedelta(weekday=calendar.FRIDAY))
print('下周三', TODAY + relativedelta(weekday=WE(+1))) # 如果今天为周三则返回今天
print('下周三', TODAY + relativedelta(days=+1, weekday=WE(+1))) # 即使今天周三也返回下周三
print('这个月最后的周五', TODAY + relativedelta(day=31, weekday=FR(-1)))
print('距离下个世纪还有', relativedelta(datetime(2100, 1, 1), TODAY)) # 作差
print('2020年母亲节', datetime(2020, 5, 1) + relativedelta(weekday=SU(+2))) # 公历5月第2个周日是母亲节
print('XerCis几岁了', relativedelta(NOW, datetime(1997, 6, 19, 12, 0)))
print('今年第260天的日期', date(2020, 1, 1) + relativedelta(yearday=260))
处理不同天数的月份永远不会跨越月的边界,年同理
from datetime import date
from dateutil.relativedelta import relativedelta
# 处理不同天数的月份永远不会跨越月的边界
print(date(2003, 1, 27) + relativedelta(months=+1)) # 2003-02-27
print(date(2003, 1, 31) + relativedelta(months=+1)) # 2003-02-28
print(date(2003, 1, 31) + relativedelta(months=+2)) # 2003-03-31
# 年同理
print(date(2000, 2, 28) + relativedelta(years=+1)) # 2001-02-28
print(date(2000, 2, 29) + relativedelta(years=+1)) # 2001-02-28
from dateutil import parser
d = parser.isoparse('2021-06-10T15:10:30+08:00')
print(type(d))
print(d)
# <class 'datetime.datetime'>
# 2021-06-10 15:10:30+08:00