Thrastylon
Thrastylon

Reputation: 990

Can I easily parse datetimes independently of my machine?

In python I like the datetime module of the standard library to parse timestamps. However, some of the format codes depend on the locale set for the machine where it's run, which makes the code fragile:

from datetime import datetime

string = "08 Aug 2024 01:45 PM"
fmt = "%d %b %Y %I:%M %p"

datetime.strptime(string, fmt)  # on an American computer
# datetime(2024, 8, 8, 13, 45)

datetime.strptime(string, fmt)  # on an French computer
# ValueError: time data '08 Aug 2024 01:45 PM' does not match format '%d %b %Y %I:%M %p'

Note: The equivalent in French is 08 aoû 2024 01:45 (different month name and no AM/PM)

Is there a more robust way to systematically parse timestamps?


At the moment, I went with a context manager setting my locale temporarily to fully control the process, but it feels like I'm missing a better tool for doing the same job.

from contextlib import contextmanager

@contextmanager
def locale_context(locale: str):
    import locale as l

    saved_loc = l.getlocale()
    l.setlocale(l.LC_ALL, locale)
    try:
        yield l.getlocale()
    finally:
        l.setlocale(l.LC_ALL, saved_loc)

def strptime(x: str, fmt: str, *, locale: str) -> datetime:
    """An equivalent of the standard strptime, with a way to fix the locale."""
    with locale_context(locale):
        return datetime.strptime(x, fmt)

strptime(string, fmt, locale="en_US")  # on an American computer
# datetime(2024, 8, 8, 13, 45)

strptime(string, fmt, locale="en_US")  # on an French computer
# datetime(2024, 8, 8, 13, 45)

Upvotes: 2

Views: 85

Answers (0)

Related Questions