holly liu
holly liu

Reputation: 93

How do I convert days into years and months in python?

How do I convert days into years and months and days in python? for example: if someone were to be 5,538 days old. how can I display that through years and months and days like this : 15 years old 2 months and 1 day

this is to get user's input

print "Please enter your birthday"
bd_year = int(raw_input("Year: "))
bd_month = int(raw_input("Month: "))
bd_day = int(raw_input("Day: "))

from datetime import date
now = date.today()

birthdate = date(int(bd_year), int(bd_month), int(bd_day))
age_in_days = now - birthdate

print "Your age is %s" % age_in_days

now I need to calculate the person's birthday in years and months and days

Upvotes: 6

Views: 48533

Answers (3)

suleman tariq
suleman tariq

Reputation: 1

#!/bin/bash

echo "bash pid: $$" echo "jobs: $(jobs -l)"

for pid in $(pgrep long-running.sh) do echo "STOPPING pid $pid..." kill -s SIGSTOP $pid

if [[ $? -eq 0 ]]; then echo "pid $pid is stopped..." else echo "pid $pid is not stopped..." fi

echo "Running pid $pid" kill -s SIGCONT $pid

if [[ $? -eq 0 ]]; then echo "$pid is stopped" else echo "pid $pid is running" fi done if the pid is running the code will stop if stopped it will run instructions fire up a process where i have put the pid you put your pid

Upvotes: -4

A.Serag
A.Serag

Reputation: 81

Using dateutil.relativedelta.relativedelta is very efficient here: Except for using .months or .days.

because rdelta.months gives you the remaining months after using full years, it doesn't give you the actual difference in months. You should convert years to months if you need to see the difference in months.

def deltamonths(x):
       rdelta = relativedelta(now, birthdate)
       return rdelta.years*12 + rdelta.months

Upvotes: 7

Anand S Kumar
Anand S Kumar

Reputation: 90889

How about using dateutil.relativedelta.relativedelta from the dateutil library? For example:

from dateutil.relativedelta import relativedelta
rdelta = relativedelta(now, birthdate)
print 'Age in years - ', rdelta.years
print 'Age in months - ', rdelta.months
print 'Age in days - ', rdelta.days

Upvotes: 18

Related Questions