dateutil库是一个处理时间的工具库。本地自带,一般不用再次安装。
1、直接在某个时间点上直接修改年份、月份等信息。
示例代码:
from dateutil.relativedelta import relativedelta
from datetime import datetime
now_time = datetime.now()
print(now_time)
# 将当前时间年份增加3年或减少3年,
# alter_year = relativedelta(years=-3)
alter_year = relativedelta(years=3)
# aa = now_time - alter_year
aa = now_time + alter_year
print(aa)
# months, weeks, days, hours, minutes, seconds, microseconds方法同years
"""官方文档解释:
years, months, weeks, days, hours, minutes, seconds, microseconds:
Relative information, may be negative (argument is plural); adding
or subtracting a relativedelta with relative information performs
the corresponding arithmetic operation on the original datetime value
with the information in the relativedelta.
"""
# 将当前时间年份直接更改为某个具体年份
alter_year = relativedelta(year=2010)
# bb = now_time - alter_year
bb = now_time + alter_year
print(bb)
# month, day, hour, minute, second, microsecond方法同year
""" 官方文档解释:
year, month, day, hour, minute, second, microsecond:
Absolute information (argument is singular); adding or subtracting a
relativedelta with absolute information does not perform an arithmetic
operation, but rather REPLACES the corresponding value in the
original datetime with the value(s) in relativedelta.
"""
运行结果:
2、日期转换,字符串日期转为datetime
示例代码:
from dateutil.parser import parse # 日期解析器
print(parse("Jul 15 2022 13:00:36")) # 月份也可全称,如july,January
print(parse('20220717'))
print(parse('2022-07-17'))
print(type(parse('2022-07-17')))
运行结果:
3、计算时间差:如计算一个人出生到现在的时间
示例代码:
from dateutil.relativedelta import relativedelta
from datetime import date
# 1.第一种方式
today = date.today()
print(today)
birthday = date(year=2020, month=1, day=1) # 假设出生日期为2020-1-1
print(birthday)
diffday = (today - birthday) # 今天和出生日期计算相差天数
print(diffday)
print(diffday.days) # 只能计算出天
# 2.第二种方式
# 下面可计算两个日期中间相差几年,几个月和几天
diff = relativedelta(today, birthday)
print(diff) # relativedelta(years=+2, months=+7, days=+19) 2岁7个月19天
print(diff.years) # 年
print(diff.months) # 月
print(diff.days) # 日
运行结果:
4、获取接下来每周周几的日期
示例代码:
from dateutil.rrule import rrule, WEEKLY
from datetime import date, datetime
next_wednesday = date(year=2022, month=8, day=20) # 设置下一个周六,2022-08-20
# next_wednesday = datetime(2022, 8, 20)
data = list(rrule(WEEKLY, count=10, dtstart=next_wednesday))
# 上面rrule函数中WEEKLY表示频次,即每周,count表示计算的数据数为10个
# dtstart即起始日 byweekday可以指定MO,TU,WE,TH,FR,SA,SU。即周一到周日。
for one in data:
print(one, '------>', one.strftime('%Y-%m-%d'))
运行结果:
具体更多功能详见源码。