Parsing Time with Pendulum: Simplify Your Date and Time Operations

Datatypes Mar 19, 2026

Parsing Time with Pendulum: Simplify Your Date and Time Operations

Parsing dates and times from messy strings (logs, APIs, CSVs, user input) is one of the most frustrating yet frequent tasks in data science. The pendulum library makes this dramatically easier, more readable, and more reliable than the standard datetime module. In 2026, Pendulum remains a favorite for developers who want human-friendly, timezone-aware parsing without writing complex format strings or error-prone try/except blocks.

TL;DR — Why Use Pendulum for Parsing

  • Extremely flexible pendulum.parse() handles ISO 8601 strictly, and many other formats with strict=False
  • Built-in timezone support with timezone parameter
  • Clean, readable API compared to datetime.strptime()
  • Perfect for real-world messy data sources

1. Basic Parsing with Pendulum

import pendulum

# ISO 8601 parses directly; other formats need strict=False
dt1 = pendulum.parse("2026-03-19")
dt2 = pendulum.parse("March 19th, 2026 3:45 PM", strict=False)
dt3 = pendulum.parse("19/03/2026 15:45:30", strict=False)
dt4 = pendulum.now("UTC").subtract(hours=3)   # relative times are built, not parsed

print(dt1)
print(dt2)
print(dt3)
print(dt4)

2. Timezone-Aware Parsing

# Parse with explicit timezone
utc_time = pendulum.parse("2026-03-19 14:30:00", tz="UTC")
ny_time = pendulum.parse("2026-03-19 14:30:00", tz="America/New_York")

print(utc_time)
print(ny_time)

# Convert between timezones
ny_time_in_utc = ny_time.in_timezone("UTC")

3. Real-World Data Science Examples

import pandas as pd
import pendulum

# In practice this would come from pd.read_csv("logs.csv")
df = pd.DataFrame({
    "timestamp": ["2026-03-19T14:30:00", "2026-03-19 15:05:12", None],
    "event_time": ["2026-03-19T14:29:58Z", "2026-03-19T15:05:10Z", "2026-03-19T16:00:00Z"],
})

# Example 1: Parse messy log timestamps
df["parsed_time"] = df["timestamp"].apply(
    lambda x: pendulum.parse(x, tz="UTC") if pd.notna(x) else None
)

# Example 2: Extract components after parsing
df["hour"] = df["parsed_time"].apply(lambda x: x.hour if x else None)
df["day_of_week"] = df["parsed_time"].apply(lambda x: x.day_of_week if x else None)

# Example 3: Minutes elapsed since each event
df["time_ago"] = df["event_time"].apply(lambda x: pendulum.parse(x, tz="UTC"))
df["minutes_ago"] = df["time_ago"].apply(lambda x: (pendulum.now("UTC") - x).in_minutes())

4. Best Practices in 2026

  • Use pendulum.parse() for ISO strings, adding strict=False for other common formats
  • Always specify tz parameter for timezone-aware results
  • Combine with pandas .apply() for vectorized parsing on large DataFrames
  • Use pendulum.now(tz=...) instead of datetime.now()
  • Fallback to standard datetime or dateutil only for very specific edge cases

Strict vs Lenient Parsing

By default pendulum.parse() is strict: it accepts ISO 8601 and closely related formats and raises ParserError for anything else. Passing strict=False lets it fall back to the more lenient dateutil parser, which understands strings like "March 19th, 2026 3:45 PM". Lenient parsing is convenient but can guess: "03/04/2026" may be read month-first. When you know the format, pendulum.from_format() removes all guessing. Relative phrases such as "3 hours ago" are not parsed; build them with now().subtract(hours=3).

Strings that carry an offset, such as 2026-03-19T14:30:00+05:00, keep that offset after parsing; strings without one are interpreted as UTC unless you pass tz=. Normalising everything with in_timezone("UTC") straight after parsing gives you a single, comparable column that sorts and subtracts correctly, and you can convert back to a local zone whenever you display the values.

Worked Example: Parse Defensively

import pendulum
from pendulum.parsing.exceptions import ParserError

raw = ["2026-03-19T14:30:00+05:00", "19/03/2026 15:45", "not a date", "2026-03-19"]

def to_utc(text):
    try:
        return pendulum.parse(text).in_timezone("UTC")
    except ParserError:
        pass
    try:
        return pendulum.from_format(text, "DD/MM/YYYY HH:mm", tz="UTC")
    except ValueError:
        return None

for text in raw:
    print(f"{text!r:30} -> {to_utc(text)}")

The function tries the strict ISO parser first, then one explicitly known format, and returns None for anything it cannot read, so bad input is visible instead of silently misinterpreted.

Common Mistakes

  • Expecting parse() to read any text by default: non-ISO strings need strict=False or from_format()
  • Trusting lenient parsing for ambiguous day/month strings
  • Forgetting tz=: strings without an offset are treated as UTC

Quick Summary

  • Strict ISO parsing by default; strict=False for other formats
  • from_format() when the format is known
  • Build relative times with add()/subtract()

Conclusion

Parsing time with Pendulum makes one of the most painful parts of data science work simple, reliable, and enjoyable. In 2026, its flexible parse() function, built-in timezone support, and clean API make it the preferred choice for handling logs, CSVs, APIs, and any source of messy datetime strings.

Next steps:

  • Try replacing your current date parsing code with pendulum.parse() on one messy dataset and enjoy the simplicity

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices