Python Forum

Full Version: How to convert dates in odd format to months
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:

Output:
0d 6d 7d 1w, 3d 7w, 5d 4m 5m
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?
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}")
Output:
0d => time in days: 0, time in full months: 0 6d => time in days: 6, time in full months: 0 7d => time in days: 7, time in full months: 0 1w, 3d => time in days: 10, time in full months: 0 7w, 5d => time in days: 54, time in full months: 1 4m => time in days: 120, time in full months: 4 5m => time in days: 150, time in full months: 5
Thank you! That worked wonderfully.