dateutil
模块扩展了Python标准库中的
datetime
模块,提供了更广泛的日期和时间处理功能。它支持解析多种日期时间格式、计算日期差异、处理时区转换、生成重复事件规则等高级功能。
「安装」
pip install python-dateutil
「使用」
「解析多种日期格式」
from dateutil import parser
date_str1 = "2023-11-15"
date_str2 = "15th November, 2023"
parsed_date1 = parser.parse(date_str1)
parsed_date2 = parser.parse(date_str2)
print(f"Parsed Dates: {parsed_date1}, {parsed_date2}")「计算两个日期之间的差异」
from datetime import datetime
from dateutil import relativedelta
start_date = datetime(2023, 1, 1)
end_date = datetime(2023, 12, 31)
difference = relativedelta(end_date, start_date)
print(f"Year Difference: {difference.years} years, {difference.days} days")「获取下一个星期几的日期」
from datetime import timedelta
from dateutil.relativedelta import relativedelta, MO
today = datetime.today()
next_monday = today + relativedelta(weekday=MO(+1))
print(f"Next Monday: {next_monday}")「创建时区感知的日期时间对象」
from datetime import datetime
from dateutil import tz
local_time = datetime.now()
local_tz = tz.tzlocal()
localized_date = local_time.replace(tzinfo=local_tz)
print(f"Localized Time: {localized_date}")「转换UTC时间到本地时间」
from datetime import datetime
from dateutil import tz
utc_time = datetime.utcnow().replace(tzinfo=tz.tzutc())
local_time = utc_time.astimezone(tz.tzlocal())
print(f"Local Time: {local_time}")「计算日期时间的增量」
from datetime import datetime
from dateutil.relativedelta import relativedelta
event_date = datetime(2023, 11, 15)
days_later = event_date + relativedelta(days=+10)
print(f"10 Days Later: {days_later}")「处理重复事件」
from datetime import datetime
from dateutil import rrule
start_date = datetime(2023, 1, 1)
rule = rrule.rrule(rrule.MONTHLY, dtstart=start_date, count=5)
for date in rule:
print(date)「确定特定日期是否为节假日」
from datetime import datetime
from dateutil import easter
today = datetime.today()
if easter.easter(today.year):
print("Today is Easter!")「格式化日期时间字符串」
from datetime import datetime
from dateutil import parser
formatted_date = parser.parse("2023-11-15 12:00:00").strftime('%A, %B %d, %Y')
print(formatted_date)「解析并修改日期时间」
from datetime import datetime
from dateutil import parser
original_date_str = "2023-11-15 12:00:00"
parsed_date = parser.parse(original_date_str)
modified_date = parsed_date.replace(year=2024)
print(f"Modified Date: {modified_date}")