diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..8229280 --- /dev/null +++ b/Pipfile @@ -0,0 +1,16 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +pelican = "*" +markdown = "*" +datefinder = "*" +typogrify = "*" +ghp-import = "*" + +[dev-packages] + +[requires] +python_version = "3.9" diff --git a/content/code/2023-10-11-python-date-conversion.md b/content/code/2023-10-11-python-date-conversion.md new file mode 100644 index 0000000..b096cca --- /dev/null +++ b/content/code/2023-10-11-python-date-conversion.md @@ -0,0 +1,49 @@ +--- +title: Convert string to duration +tags: python, conversion +--- + +I found myself wanting to convert a string to a duration (int), for some configuration. + +Something you can call like this: + +```python +string_to_duration("1d", target="days") # returns 1 +string_to_duration("1d", target="hours") # returns 24 +string_to_duration("3m", target="hours") # returns 3 * 24 * 30 +``` + +The code : + +```python +from typing import Literal + + +def string_to_duration(value: str, target: Literal["days", "hours"]): + """Convert a string to a number of hours, or days""" + num = int("".join(filter(str.isdigit, value))) + + if target == "hours": + reconvert = True + + if "h" in value: + if target == "days": + raise ValueError("Invalid duration value", value) + num = num + reconvert = False + elif "d" in value: + num = num + elif "w" in value: + num = num * 7 + elif "m" in value: + num = num * 30 + elif "y" in value: + num = num * 365 + else: + raise ValueError("Invalid duration value", value) + + if target == "hours" and reconvert: + num = num * 24 + + return num +`````` \ No newline at end of file