Snaptime

0.2.4 · maintenance · verified Thu Apr 16

Snaptime is a Python package (version 0.2.4) designed for transforming timestamps using a simple Domain Specific Language (DSL), inspired by Splunk's relative time modifiers. It provides functions to easily truncate, snap to specific time units, and apply delta transformations to datetime objects. The library has a low release cadence, with the last update in 2017.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic usage of `snap` for time manipulation and highlights the importance of `snap_tz` when dealing with timezone-aware datetimes, particularly around Daylight Saving Time (DST) changes. It includes a practical example of calculating a delivery time and showcases both naive and timezone-aware snapping.

from datetime import datetime
from snaptime import snap, snap_tz
import pytz

# Example 1: Basic snap and delta transformations
dt = datetime(2018, 10, 28, 23, 0, 0)
print(f"Original: {dt}")
print(f"Snap to day (@d): {snap(dt, '@d')}") # 2018-10-28 00:00:00
print(f"Add 3 hours (+3h): {snap(dt, '+3h')}") # 2018-10-29 02:00:00
print(f"Add 3 hours then snap to day (+3h@d): {snap(dt, '+3h@d')}") # 2018-10-29 00:00:00

# Example 2: Motivating example from docs (letter delivery time)
t_harry_throws_letter = datetime(2024, 4, 15, 15, 0, 0) # Harry throws letter at 3 PM
letter_delivery_time = snap(t_harry_throws_letter, "+8h@d+1d+11h")
print(f"\nLetter thrown: {t_harry_throws_letter}")
print(f"Letter delivered: {letter_delivery_time}")

# Example 3: Handling timezones with snap_tz
# Requires 'pytz' library
berlin_tz = pytz.timezone('Europe/Berlin')
dt_tz_aware = berlin_tz.localize(datetime(2017, 3, 26, 3, 26, 6))

# Using naive snap can lead to unexpected results during DST changes
print(f"\nTZ-aware original: {dt_tz_aware}")
print(f"snap(dt_tz_aware, '@d') (naive approach, potential DST issue): {snap(dt_tz_aware, '@d')}")

# Use snap_tz for correct timezone handling
print(f"snap_tz(dt_tz_aware, '@d', berlin_tz) (correct DST handling): {snap_tz(dt_tz_aware, '@d', berlin_tz)}")

view raw JSON →