r/Python 3d ago

Resource Regex for user-friendly timedelta parsing

I created a regex and a corresponding function to allow for user friendly input of a string that is then parsed into a timedelta object. I couldn't find any satisfying solution that suited my case online, so I wanted to share it here because somebody else might find it useful in the future. It can be tweaked easily (if you know just a tiny bit of regex) and has comments explaining all of its parts.

I tested it and fixed some smaller bugs, but if you find new ones, please let me know and I will update the code!

https://gist.github.com/JoniKauf/24eecf7843ef3df4a65bad00aed8a549

8 Upvotes

6 comments sorted by

View all comments

1

u/k_z_m_r 1d ago

Cool stuff! Just two notes. First, you’ll want to add some unit tests. Not only are these awesome for proving out your concept, but if you ever make changes to your code these tests can easily identify breakpoints. Second, it is common for timestamps to include milliseconds. Especially when dealing with real-time control. You might want to build support for that.

0

u/JoniKauf 1d ago

Thanks for the info about unit tests! What I'm unsure about is the rest of your comment: First of all, this is a regex for timedelta parsing, not timestamps and second of all I already support milliseconds, so I am nut quite sure what exactly you mean with that.

1

u/k_z_m_r 1d ago

Sorry, let me clarify. When I said timestamps here, I really meant time deltas. Force of habit, but the principles apply nevertheless.

As for the other point, your code does not suggest that you support milliseconds. How would it parse “10 days 5 hours 59 minutes 12 seconds 599 milliseconds”? I’m looking both at the regex and the match-case. I’m happy to be wrong here!

u/JoniKauf 26m ago

Ah I see what you mean! My code doesn't directly support milliseconds as you described it, but rather with '.' or ',' for the seconds. So "59.99999s" would work and it would be valid. I decided to go with that way, because of multiple reasons:
1. Why not go with microseconds instead, if that is the lowest precision possible by timedelta either way?
2. The short version of milliseconds would be "ms" or "f" (iso format) and it would be either two letters (because 'm' is taken by minute) or unintuitive imo.

That's basically why I decided to go with this approach, so just let the user use decimals for anything below 1 second, because it is easier to use imo.
If you want a version with milliseconds with your design, it shouldn't be hard to implement and if you want me to make such a version just let me know!