- Alexis Métaireau
- Journal
- Code, etc.
- Notes hebdo
- Lectures
- Projets

# Tag « conversion »

11 octobre 2023 python, conversion

# Convert string to duration

I found myself wanting to convert a string to a duration (int), for some configuration.

Something you can call like this:

    string_to_duration("1d", target="days")
    string_to_duration("1d", target="hours")
    string_to_duration("3m", target="hours")
    string_to_duration("3m", target="minutes")

The code :

    from typing import Literal

    def string_to_duration(value: str, target: Literal["days …