Skip to content

Instantly share code, notes, and snippets.

@variance
variance / str2deg.py
Created March 19, 2019 07:57
parse an angle in degrees from string to float
# first syntax is D° M' S.sss" (spaces are optional)
DMS_CRE1 = re.compile(r'''\s*(?P<deg>[+-]?\d+)[°d]\s?(?P<min>\d+)['´′m](?:\s?(?P<sec>(\d+(\.\d*)?|\.\d+))["″s])?\s*''')
# alternative syntax is D:M:S.sss (no space allowed)
DMS_CRE2 = re.compile(r'''\s*(?P<deg>[+-]?\d+):(?P<min>\d+):(?P<sec>(\d+(\.\d*)?|\.\d+))\s*''')
def str2deg(s):
"""convert a string to decimal degrees
Either a decimal number or a D:M:S.s or D°M'S.s" with an optional sign is supported.
(Degrees and minutes must be integer but fractions of arc seconds are ok.)
@variance
variance / deg2str.py
Created March 19, 2019 08:03
format angle in degrees into a DMS string
def deg2str(d, *, decimals=3, colon_separated=False):
"""convert decimal degrees to a DMS string"""
sign = '-' if d < 0 else ''
deg = int(abs(d))
min_ = int(abs(d) * 60) % 60
sec = (abs(d) * 3600) % 60
return (f"{sign}{deg:d}:{min_:02d}:{sec:.{decimals}f}" if colon_separated
else f'''{sign}{deg:d}°{min_:02d}'{sec:0{decimals + 3 if decimals else 2}.{decimals}f}"''')
@variance
variance / download_file_if_needed.py
Last active May 12, 2025 10:26
Python function to download a missing file on demand from a given URL
import os
import requests
from urllib.parse import urlparse
def download_file_if_needed(url, file_path=None):
"""Download file if it doesn't exist or is empty."""
if file_path is None:
parsed_url = urlparse(url)
filename = os.path.basename(parsed_url.path)
if not filename: