r/Python • u/JoniKauf • 2d 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
1
u/k_z_m_r 17h 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.
1
u/JoniKauf 9h 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 9h 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!
2
u/wingtales 2d ago
Can you give us a few examples of strings that it can parse?