Python 使用 python-dateutil 获取间隔时间

2023-12-21 21:23:26

当前环境:Win10 + Python3.7+ python-dateutil==2.8.2?

from datetime import datetime
# 获取当前日期
current_date = datetime.now()


from dateutil.relativedelta import relativedelta


# 计算下一年的日期
next_year_date = current_date + relativedelta(years=+1)
# 计算下一个月的日期
next_month_date = current_date + relativedelta(months=+1)
# 计算下一天的日期
next_day_date = current_date + relativedelta(days=+1)
# 计算下一时的日期
next_hour_date = current_date + relativedelta(hours=+1)
# 计算下一分的日期
next_minute_date = current_date + relativedelta(minutes=+1)
# 计算下一秒的日期
next_second_date = current_date + relativedelta(seconds=+1)

print(type(next_year_date),next_year_date)
print(type(next_month_date),next_month_date)
print(type(next_day_date),next_day_date)
print(type(next_hour_date),next_hour_date)
print(type(next_minute_date),next_minute_date)
print(type(next_second_date),next_second_date)

# 格式化日期
str_time = next_year_date.strftime('%Y-%m-%d %H:%M:%S')
print(type(str_time),str_time)


'''
运行结果:
<class 'datetime.datetime'> 2024-12-21 16:29:24.276577
<class 'datetime.datetime'> 2024-01-21 16:29:24.276577
<class 'datetime.datetime'> 2023-12-22 16:29:24.276577
<class 'datetime.datetime'> 2023-12-21 17:29:24.276577
<class 'datetime.datetime'> 2023-12-21 16:30:24.276577
<class 'datetime.datetime'> 2023-12-21 16:29:25.276577
<class 'str'> 2024-12-21 16:29:24
'''

'''
参考:
https://blog.51cto.com/u_16175514/7415349
https://zhuanlan.zhihu.com/p/341333939
https://blog.csdn.net/lilongsy/article/details/80242427
'''

文章来源:https://blog.csdn.net/yudiandian2014/article/details/135138310
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。