Skip to content

feat: custom datetime formatting in .fmt_datetime() #645

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions great_tables/_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -2081,6 +2081,7 @@
rows: int | list[int] | None = None,
date_style: DateStyle = "iso",
time_style: TimeStyle = "iso",
format_str: str | None = None,
sep: str = " ",
pattern: str = "{x}",
locale: str | None = None,
Expand Down Expand Up @@ -2109,6 +2110,10 @@
The time style to use. By default this is the short name `"iso"` which corresponds to how
times are formatted within ISO 8601 datetime values. There are 5 time styles in total and
their short names can be viewed using `info_time_style()`.
format_str
A string that specifies the format of the datetime string. This is a `strftime()` format
string that can be used to format date or datetime input. If `format=` is provided, the
`date_style=` and `time_style=` arguments are ignored.

Formatting with the `date_style` and `time_style` arguments
------------------------------------------------------------
Expand Down Expand Up @@ -2194,6 +2199,7 @@
data=self,
date_format_str=date_format_str,
time_format_str=time_format_str,
format_str=format_str,
sep=sep,
pattern=pattern,
locale=locale,
Expand All @@ -2207,6 +2213,7 @@
data: GTData,
date_format_str: str,
time_format_str: str,
format_str: str | None,
sep: str,
pattern: str,
locale: str | None,
Expand All @@ -2215,9 +2222,6 @@
if is_na(data._tbl_data, x):
return x

# From the date and time format strings, create a datetime format string
datetime_format_str = f"{date_format_str}'{sep}'{time_format_str}"

# If `x` is a string, assume it is an ISO datetime string and convert it to a datetime object
if isinstance(x, str):
# Convert the ISO datetime string to a datetime object
Expand All @@ -2227,14 +2231,24 @@
# Stop if `x` is not a valid datetime object
_validate_datetime_obj(x=x)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAICT this if / else should just stay the same, and the extra formatting logic should go below it


# Fix up the locale for `format_datetime()` by replacing any hyphens with underscores
if locale is None:
locale = "en_US"
if format_str is not None:
if locale is not None:
raise ValueError("The `format_str=` and `locale=` arguments cannot be used together.")

Check warning on line 2236 in great_tables/_formats.py

View check run for this annotation

Codecov / codecov/patch

great_tables/_formats.py#L2236

Added line #L2236 was not covered by tests

x_formatted = x.strftime(format_str)

else:
locale = _str_replace(locale, "-", "_")
# From the date and time format strings, create a datetime format string
datetime_format_str = f"{date_format_str}'{sep}'{time_format_str}"

# Fix up the locale for `format_datetime()` by replacing any hyphens with underscores
if locale is None:
locale = "en_US"
else:
locale = _str_replace(locale, "-", "_")

# Format the datetime object to a string using Babel's `format_datetime()` function
x_formatted = format_datetime(x, format=datetime_format_str, locale=locale)
# Format the datetime object to a string using Babel's `format_datetime()` function
x_formatted = format_datetime(x, format=datetime_format_str, locale=locale)

# Use a supplied pattern specification to decorate the formatted value
if pattern != "{x}":
Expand Down
22 changes: 22 additions & 0 deletions tests/test_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -1299,6 +1299,28 @@ def test_fmt_datetime():
]


def test_fmt_datetime_format_str():
df = pd.DataFrame(
{
"x": [
"2013-05-15 23:15",
"2020-05-20",
],
}
)

gt = GT(df).fmt_datetime(
columns="x",
format_str="%A, %B %d, %Y at %I:%M %p",
)

x = _get_column_of_values(gt, column_name="x", context="html")
assert x == [
"Wednesday, May 15, 2013 at 11:15 PM",
"Wednesday, May 20, 2020 at 12:00 AM",
]


def test_fmt_datetime_bad_date_style_raises():
df = pd.DataFrame(
{
Expand Down
Loading