How to convert dates in odd format to months - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to convert dates in odd format to months (/thread-33335.html) |
How to convert dates in odd format to months - lokhtar - Apr-17-2021 So I have a column called 'age' in my sql column that is inconsistent in format. It lists ages of kids in days, weeks or months. For example: What I want to do is convert that into months, like, anyone under 30 days would be 0 months, anyone between 1-2 months would be 1 month, etc. The max-age I have is seven months, so it would be changed to one of eight categories: 0,1,2,3,4,5,6,7.I was thinking of a clunky way of doing it, like searching to see if there is a 'w', and if so, remove the w and everything after the w, and take that number. Do the same for days, and then for months. But I am sure there has to be a cleaner way? RE: How to convert dates in odd format to months - bowlofred - Apr-17-2021 Maybe something like this? It assumes a month is exactly 30 days. Not correct, but pretty close.... sample = """0d 6d 7d 1w, 3d 7w, 5d 4m 5m """ period = { "d": 1, "w": 7, "m": 30, } for line in sample.splitlines(): total_time = 0 for time in line.split(", "): qty, unit = time[:-1], time[-1] qty = int(qty) total_time += qty * period[unit] months = total_time // 30 print(f"{line} => time in days: {total_time}, time in full months: {months}")
RE: How to convert dates in odd format to months - lokhtar - Apr-17-2021 Thank you! That worked wonderfully. |