81 lines
3.3 KiB
Markdown
81 lines
3.3 KiB
Markdown
For working with date and time in Python, `dateutil` is an incredibly useful library that extends the standard `datetime` module. It provides powerful extensions to the standard `datetime` module, available in the Python Standard Library. `dateutil` makes it easier to parse dates from strings, compute deltas, and handle timezone calculations, among other functionalities. Here's a concise reference guide for common use cases with `dateutil`:
|
|
|
|
# `dateutil` Reference Guide
|
|
|
|
## Installation
|
|
```
|
|
pip install python-dateutil
|
|
```
|
|
|
|
## Basic Usage
|
|
|
|
### Parsing Dates and Times from Strings
|
|
```python
|
|
from dateutil import parser
|
|
|
|
dt = parser.parse("2024-03-28 14:45:00")
|
|
print(dt)
|
|
```
|
|
|
|
### Relative Delta
|
|
Calculating differences between dates, adding or subtracting days, weeks, months, years, etc., in a way that considers the calendar's rules.
|
|
```python
|
|
from dateutil.relativedelta import relativedelta
|
|
|
|
# Add 1 month to a specific date
|
|
new_date = dt + relativedelta(months=+1)
|
|
print(new_date)
|
|
|
|
# Calculate the difference between two dates
|
|
date1 = parser.parse("2024-03-28")
|
|
date2 = parser.parse("2024-04-28")
|
|
delta = relativedelta(date2, date1)
|
|
print(f"Years: {delta.years}, Months: {delta.months}, Days: {delta.days}")
|
|
```
|
|
|
|
### Handling Time Zones
|
|
`dateutil` simplifies the work with time zones, converting between time zones, and making timezone-aware datetime objects.
|
|
```python
|
|
from dateutil import tz
|
|
|
|
# Get a timezone-aware datetime
|
|
eastern = tz.gettz('America/New_York')
|
|
dt_aware = dt.replace(tzinfo=tz.gettz('UTC')).astimezone(eastern)
|
|
print(dt_aware)
|
|
|
|
# Convert a timezone-aware datetime to another timezone
|
|
paris_tz = tz.gettz('Europe/Paris')
|
|
dt_in_paris = dt_aware.astimezone(paris_tz)
|
|
print(dt_in_paris)
|
|
```
|
|
|
|
### Recurring Events with `rrule`
|
|
`dateutil.rrule` provides support for calculating recurring events based on very flexible recurrence rules, similar to those used in calendars.
|
|
```python
|
|
from dateutil.rrule import rrule, MONTHLY
|
|
from datetime import datetime
|
|
|
|
# Define a rule for recurring events (e.g., monthly)
|
|
rule = rrule(MONTHLY, dtstart=datetime(2024, 1, 1), count=5)
|
|
|
|
# List all occurrences
|
|
for dt_occurrence in rule:
|
|
print(dt_occurrence)
|
|
```
|
|
|
|
## Advanced Features
|
|
|
|
### Working with Holidays
|
|
While `dateutil` itself does not directly provide holiday functionality, its powerful parsing and relative delta features can be used in combination with custom holiday definitions or other libraries to handle holidays in applications.
|
|
|
|
### Fuzzy Parsing
|
|
When parsing dates from sources with varying formats or including unwanted characters, `dateutil.parser.parse` supports fuzzy parsing to ignore unknown tokens.
|
|
```python
|
|
dt_fuzzy = parser.parse("Thursday, March 28, 2024 at 14:45:00", fuzzy=True)
|
|
print(dt_fuzzy)
|
|
```
|
|
|
|
`dateutil` enhances the datetime handling capabilities of Python programs, making it easier to perform complex date and time calculations, parsing, and formatting. Its wide range of functionalities addresses most of the common challenges encountered when working with date and time in Python, making it an essential tool for any Python developer dealing with time data.
|
|
|
|
|
|
Dateutil's comprehensive suite of features for dealing with temporal data simplifies many tasks that would otherwise require significant manual coding, especially when dealing with time zones, parsing dates from strings, and calculating date ranges or recurring events. |