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}")