Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python date libraries parse, convert, and calculate dates and times beyond what the standard datetime module covers. These libraries read the dates in logs, forms, and data files and convert them between time zones for reports and schedules.
python-dateutil extends Python's standard datetime module. The package installs as python-dateutil and imports as dateutil. parser.parse reads a date string in almost any format and returns a datetime. Calendar math comes from relativedelta, which adds units such as next month or the last week of a month. For repeating dates, rrule follows a superset of the iCalendar recurrence rules.
Downloads / mo
1.2B
Stars
2.6K
Last release
4.0.0
License
BSD-3-Clause
Strengths
Month and year offsets.Add or subtract calendar months and years with relativedelta.
Recurring dates.Build schedules by frequency, weekday, and day of the month with rrule.
Limitations
Guesses on ambiguous dates.Set dayfirst or yearfirst so numeric dates parse in the expected order.
Skips invalid recurrence dates.A monthly rule on a day that some months lack skips those months.
def eval(self) -> datetime:
dttm_expression, unit = self.value
dttm = dttm_expression.eval()
if unit == "year":
return dttm.replace(
month=12, day=31, hour=0, minute=0, second=0, microsecond=0
)
if unit == "quarter":
# Both arguments are passed to a single `replace` so the day is # never briefly out of range for the new month (e.g. the 31st # moving into a 30-day quarter-end month). last_month = 3 * ((dttm.month - 1) // 3) + 3
return dttm.replace(
month=last_month,
day=calendar.monthrange(dttm.year, last_month)[1],
hour=0,
minute=0,
second=0,
microsecond=0,
)
if unit == "month":
return dttm.replace(
day=calendar.monthrange(dttm.year, dttm.month)[1],
hour=0,
minute=0,
second=0,
microsecond=0,
)
if unit == "day":
# The last day of a day is that same day. Truncating to midnight # keeps the result consistent with every other unit here, which # all return the final day at midnight rather than at its end. return dttm.replace(hour=0, minute=0, second=0, microsecond=0)
# unit == "week": mon = dttm - relativedelta(days=dttm.weekday())
mon = mon.replace(hour=0, minute=0, second=0, microsecond=0)
return mon + relativedelta(days=6)
pytz
pytz brings the Olson time zone database into Python. timezone('US/Eastern') returns a zone object, and its localize method attaches that zone to a naive datetime. After arithmetic that crosses a daylight saving change, normalize corrects the offset. The README marks pytz as deprecated and points newer Python versions to the standard zoneinfo module, the type tzlocal returns.
Downloads / mo
508.9M
Stars
399
Last release
2026.6
License
MIT
Strengths
Fixes DST arithmetic.Call normalize() after arithmetic on local times that cross a daylight-saving change.
Limitations
Deprecated by its maintainer.On Python 3.9 or later, use the standard zoneinfo module in new code.
The tzinfo argument misbehaves.Build local times with localize(), not the datetime tzinfo argument.
def make_aware(value, timezone=None, is_dst=None):
"""Make a naive datetime.datetime in a given time zone aware."""
if timezone is None:
timezone = get_current_timezone()
if _is_pytz_zone(timezone):
# This method is available for pytz time zones. return timezone.localize(value, is_dst=is_dst)
else:
# Check that we won't overwrite the timezone of an aware datetime. if is_aware(value):
raise ValueError(
"make_aware expects a naive datetime, got %s" % value)
# This may be wrong around DST changes! return value.replace(tzinfo=timezone)
tzlocal
tzlocal finds the machine's local time zone, which neither pytz nor zoneinfo can report on their own. get_localzone returns a tzinfo object even when the system has no zone name configured. A second function, get_localzone_name, returns only the name, such as Europe/Paris, when one is set. On Unix the library reads files such as /etc/localtime and /etc/timezone. Current versions return zoneinfo objects instead of pytz objects.
Downloads / mo
192.0M
Stars
221
Last release
5.4.5
License
MIT
Strengths
Works without a zone name.get_localzone() returns a timezone even when the system has no zone name configured.
Limitations
Returns zoneinfo, not pytz.Stay on version 4.0 for code that still needs pytz objects.
Docker setups often break.Set the TZ environment variable in containers so tzlocal finds the right zone.
Arrow provides a drop-in replacement for Python's datetime that is timezone-aware and set to UTC by default. arrow.get parses ISO strings and timestamps, shift moves a value by hours, days, or weeks, and to converts it to another time zone. For display, humanize returns phrases such as "an hour ago" in many languages. The README credits moment.js, the JavaScript date library, as its inspiration.
Downloads / mo
73.7M
Stars
9.1K
Last release
1.4.0
License
Apache-2.0
Strengths
Chains timezone conversions.Parse a value, shift it by calendar units, and convert its timezone in one chain.
Humanizes in many locales.Pass a locale to humanize() to get phrases like "an hour ago" in that language.
Limitations
Shifts move nonexistent times.Shifts into a daylight-saving gap move to a real time by default. Pass check_imaginary=False to skip that.
def scheduler(broker: Broker = None):
"""
Creates a task from a schedule at the scheduled time and schedules next run
"""
if not broker:
broker = get_broker()
close_old_django_connections()
try:
database_to_use = {"using": Conf.ORM} if not Conf.HAS_REPLICA else {}
with db.transaction.atomic(**database_to_use):
for s in (
Schedule.objects.select_for_update()
.exclude(repeats=0)
.filter(next_run__lt=timezone.now())
.filter(
db.models.Q(cluster__isnull=True) | db.models.Q(cluster=Conf.PREFIX)
)
):
args = ()
kwargs = {}
# get args, kwargs and hook if s.kwargs:
try:
# eval should be safe here because dict() kwargs = eval(f"dict({s.kwargs})")
except SyntaxError:
kwargs = {}
if s.args:
args = ast.literal_eval(s.args)
# single value won't eval to tuple, so: if type(args) != tuple:
args = (args,)
q_options = kwargs.get("q_options", {})
if s.hook:
q_options["hook"] = s.hook
# set up the next run time if s.schedule_type != s.ONCE:
next_run = arrow.get(s.next_run)
while True:
if s.schedule_type == s.MINUTES:
next_run = next_run.shift(minutes=+(s.minutes or 1))
elif s.schedule_type == s.HOURLY:
next_run = next_run.shift(hours=+1)
elif s.schedule_type == s.DAILY:
next_run = next_run.shift(days=+1)
elif s.schedule_type == s.WEEKLY:
next_run = next_run.shift(weeks=+1)
elif s.schedule_type == s.MONTHLY:
next_run = next_run.shift(months=+1)
elif s.schedule_type == s.QUARTERLY:
next_run = next_run.shift(months=+3)
elif s.schedule_type == s.YEARLY:
next_run = next_run.shift(years=+1)
elif s.schedule_type == s.CRON:
if not croniter:
raise ImportError(
_(
"Please install croniter to enable cron expressions"
)
)
next_run = arrow.get(
croniter(s.cron, localtime()).get_next()
)
if Conf.CATCH_UP or next_run > arrow.utcnow():
break
# arrow always returns a tz aware datetime, and we don't want # this when we explicitly configured django with USE_TZ=False s.next_run = (
next_run.datetime
if settings.USE_TZ
else next_run.datetime.replace(tzinfo=None)
)
s.repeats += -1
# send it to the cluster scheduled_broker = broker
try:
scheduled_broker = get_broker(q_options["broker_name"])
except: # invalid broker_name or non existing broker with broker_name
pass
q_options["broker"] = scheduled_broker
q_options["group"] = q_options.get("group", s.name or s.id)
kwargs["q_options"] = q_options
s.task = django_q.tasks.async_task(s.func, *args, **kwargs)
# log it if not s.task:
logger.error(
_(
f"{current_process().name} failed to create a task from schedule [{s.name or s.id}]"
)
)
else:
logger.info(
_(
f"{current_process().name} created a task from schedule [{s.name or s.id}]"
)
)
# default behavior is to delete a ONCE schedule if s.schedule_type == s.ONCE:
if s.repeats < 0:
s.delete()
continue
# but not if it has a positive repeats s.repeats = 0
# save the schedule s.save()
except Exception as e:
logger.error(e)
Pendulum
Pendulum's DateTime class inherits from Python's datetime, so it works where a datetime is expected. Every instance is timezone-aware and in UTC by default. in_timezone converts a value to another zone, add and subtract move it by calendar units, and diff_for_humans describes the gap from now, such as "two minutes ago". Arithmetic across a daylight saving change returns a time that exists on the clock. Arrow covers the same ground with its own type, while Pendulum stays a subclass of datetime.
Downloads / mo
58.3M
Stars
6.7K
Last release
3.3.0
License
MIT
Strengths
Converts timezones in one call.Call in_timezone() to move a date into another timezone.
Localized relative times.Pass locale to diff_for_humans() to change the language for one call.
Limitations
Strict parsing by default.Pass strict=False to fall back to the dateutil parser for other formats.
Some drivers check the type.Database drivers such as PyMySQL and mysqlclient check an object's exact type, so they need an adapter registered for DateTime.
def parse_timezone(name: str | int) -> FixedTimezone | Timezone:
"""
Parse timezone and return one of the pendulum Timezone.
Provide the same interface as ``pendulum.timezone(name)``
:param name: Either IANA timezone or offset to UTC in seconds.
:meta private:
"""
if _PENDULUM3:
# This only presented in pendulum 3 and code do not reached into the pendulum 2 return pendulum.timezone(name) # type: ignore[operator]
# In pendulum 2 this refers to the function, in pendulum 3 refers to the module return pendulum.tz.timezone(name) # type: ignore[operator]
dateparser
dateparser turns human-readable date strings into datetime objects through one function, dateparser.parse. Absolute dates, relative phrases such as "two weeks ago", and timestamps all parse, in more than two hundred language locales. The language is detected automatically unless languages sets it. Formats passed in date_formats are tried before the general parser. Compared with parsedatetime, dateparser returns a datetime directly instead of a time tuple.
Downloads / mo
44.1M
Stars
2.9K
Last release
1.5.0
License
BSD-3-Clause
Strengths
Parses many languages.Pass languages when they are known, and dateparser skips detection.
Parses relative dates.Turns phrases like "In two months" into a datetime.
Limitations
Fills in missing date parts.Set STRICT_PARSING to reject dates with missing parts.
def __parser(ds, date_order):
"""
Call dateparser.parse with a particular date ordering
"""
return dateparser.parse(
ds,
settings={
"DATE_ORDER": date_order,
"PREFER_DAY_OF_MONTH": "first",
"RETURN_AS_TIMEZONE_AWARE":
True
}
)
holidays
holidays generates the public holidays of a country, or of a subdivision such as a state or province, as a dict-like object. holidays.country_holidays("US") returns the calendar. Testing a date, a date string, or a timestamp with in says whether that day is a holiday, while get returns the holiday's name. Calendars cover more than two hundred country codes. For markets, financial_holidays("NYSE") returns stock exchange closing days.
Downloads / mo
32.7M
Stars
2.0K
Last release
0.109
License
MIT
Strengths
Stock exchange calendars.Call financial_holidays("NYSE") to get trading holidays for an exchange.
Names in other languages.Pass language to get holiday names in the language users read.
Limitations
Observed days included by default.Set observed=False to get only the official dates, and test it for the country in question.
def make_holidays_df(
year_list: list[int],
country: str,
province: str | None = None,
state: str | None = None, # unused
) -> pd.DataFrame:
"""Make dataframe of holidays for given years and countries
Parameters
---------- year_list: a list of years
country: country name
province: province name
Returns
------- Dataframe with 'ds' and 'holiday', which can directly feed
to 'holidays' params in Prophet
"""
country_holidays = get_country_holidays_class(country)
holidays = country_holidays(expand=False, language="en_US", subdiv=province, years=year_list)
holidays_df = pd.DataFrame(
[(date, holidays.get_list(date)) for date in holidays],
columns=["ds", "holiday"],
)
holidays_df = holidays_df.explode("holiday")
holidays_df.reset_index(inplace=True, drop=True)
holidays_df["ds"] = pd.to_datetime(holidays_df["ds"])
return holidays_df
parsedatetime
parsedatetime parses human-readable date and time text, such as "tomorrow", with a Calendar object. Calendar.parse returns a time tuple and a status code, and the tuple needs one more step to become a datetime. For a timezone-aware result, parseDT takes a pytz zone and returns a datetime directly.
Downloads / mo
25.7M
Stars
710
Last release
2.6
License
Apache-2.0
Strengths
Parses everyday phrases.Create a Calendar and call parse() on text such as "tomorrow".
Limitations
Returns a time tuple.parse() returns a time tuple and a status, so convert it before using it as a datetime.
Timezones come from pytz.Pass a pytz timezone to parseDT() to get a timezone-aware result.
def parse_human_datetime(human_readable: str) -> datetime:
"""Returns ``datetime.datetime`` from human readable strings"""
x_periods = r"^\s*([0-9]+)\s+(second|minute|hour|day|week|month|quarter|year)s?\s*$"
if re.search(x_periods, human_readable, re.IGNORECASE):
raise TimeRangeAmbiguousError(human_readable)
try:
default = datetime(year=datetime.now().year, month=1, day=1)
dttm = parse(human_readable, default=default)
except (ValueError, OverflowError) as ex:
cal = parsedatetime.Calendar()
parsed_dttm, parsed_flags = cal.parseDT(human_readable)
# 0 == not parsed at all if parsed_flags == 0:
logger.debug(ex)
raise TimeRangeParseFailError(human_readable) from ex
# when time is not extracted, we 'reset to midnight' if parsed_flags & 2 == 0:
parsed_dttm = parsed_dttm.replace(hour=0, minute=0, second=0)
dttm = dttm_from_timetuple(parsed_dttm.utctimetuple())
return dttm
FAQ
Start with the standard datetime and zoneinfo modules, and add python-dateutil, with 1.2B downloads a month, for parsing and month math. Choose Arrow or Pendulum for a friendlier API, or dateparser for dates written in other languages.
It adds a forgiving string parser, relativedelta for month and year offsets, rrule for recurring dates, and extra timezone helpers. It works on standard datetime objects instead of replacing them.
Add relativedelta(months=n) from python-dateutil to the date. When the target month is shorter, the result lands on the last day of that month. A plain timedelta counts days, so it can't add calendar months.
Use datetime.strptime when the exact format is known. Use dateutil.parser.parse for most other formats, and dateparser for relative phrases such as "two weeks ago" or dates in other languages.
Use zoneinfo. The pytz maintainer marks pytz as deprecated and points modern Python projects to the standard zoneinfo module. Keep pytz only for older code that depends on its localize() API.
Use holidays. Build a calendar with holidays.country_holidays("US") and test a date with in. Call holidays.financial_holidays("NYSE") for stock exchange holidays.
For coding agents
Found your date and time library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.