date using either raw_input() or input() coming up as integer - python-2.7

New to Python and have read so many other SO questions that I feel like I am missing something with how to massage user input to string format. I have this simple code and I get the AttributeError: 'int' object has no attribute 'split' so I added exception handiling and am getting error everytime. I have tried almost everything with the str(), datetime() and std.readline() and nothing.
def dateConverter(userDate):
try:
#split the substrings for month day year
date = userDate.split("/")
#day
day = date[:2]
#month
month = date[3:5]#[ beginning : beginning + LENGTH]
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
for key,value in months:
month=value
#year
year = date[4:]
print(str(month + ' ' + day + ',' + year))
return True
except:
print('Error')
return False
print('Enter a date in the format: mm/dd/yyyy \n')
userInput = raw_input()
dateConverter(userInput)
main()
Note: I have both Python27 and Python34 installed on Win7
Edit
vaibhav-sagar was correct, I wasn't slicing the string the right way and had nothing to do with the input. Although, I have Python27 & Python34 installed and even though I set my variable path to Python34 I have to use raw_input() which I heard was deprecated in Python34 so look out for that too. That is what was stumping me! Sorry, this was my second look at Python so it was really new territory. I actually got the slicing examples from another SO answer so that is what I get for assuming. Here is the solution:
#custom date converter func
def dateConverter(userDate):
try:
#split the substrings for month day year
date = userDate.split("/")
#day
day = date[1]#[ beginning : beginning + LENGTH]
#month
month = date[0]
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
month=months[int(month)]
#year
year = date[2]
print(month + ' ' + day + ',' + year)
return True
except:
print('Error')
return False
Next step is to validate using re to validate the date is valid

I am using Python 3.3.5 and getting a different error. An exception is being raised at
for key, value in months:
Because iterating over a dictionary yields only keys, and not keys and values. What you want can be accomplished by:
for key, value in months.items():
More generally, your issues seem unrelated to your massaging of user input. This can be verified by using IDLE or another REPL. For example:
>>> someDate = '12/10/2014'
>>> date = someDate.split('/')
>>> date
['12', '10', '2014']
>>> day = date[:2]
>>> day
['12', '10']
>>> month = date[3:5]
>>> month
[]
>>> year = date[4:]
>>> year
[]
Python's slice syntax is doing something different to what I think you want. I also think you don't need a for loop, instead you can do:
month = months[int(month)]
This will assign the month name to month, like you expect. A function that does what I think you want would look something like this:
def dateConverter(userDate):
#split the substrings for month day year
date = userDate.split("/")
#day
day = date[1]
#month
month = date[0]
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
month = months[int(month)]
#year
year = date[2]
print(str(month + ' ' + day + ',' + year))
return True
I hope that helps.

Related

How to get only date after subtraction of two date field

I'm trying to have subtraction of two data fields and the result in days. But I'm having time also at the output. How do I get only days not the time.
Here is my code:
class ItemTable(models.Model):
expdate = models.DateField("EXP Date", null=True, blank=True)
def days_to_exp(self):
if self.expdate:
now = datetime.date.today()
exp = str(self.expdate - now)
if exp > "1":
return exp
elif exp < "1" and exp > "0":
return "Today"
else:
return "Expired"
output:
12 days, 0:00:00,
4 days, 0:00:00... etc
I just want the result as:
12 days,
4 days..... etc
The result of subtracting one datetime.date from another is a timedelta object. You can access the .days attribute of that timedelta object to get what you're after.
> today = datetime.now().date()
> tomorrow = today + timedelta(days=1)
> (tomorrow - today).days
1
> (today - tomorrow).days
-1
Result of subtraction between datetime.date instances is an object with type of datetime.timedelta that represents a duration not datetime.date nor datetime.datatime. you can get how long a timedelta is by accessing it's .days property.
for example:
result = now().today() - (now()+timedelta(days=10))
assert(result.days==10)

How do I get today's date automatically as an integer in python

I want to write a code where it returns user's age when user enters his age in YYYYmmdd format. I have noticed that error lies in the line when I need to get the today's date as an integer but cannot convert strftime to an integer. I am using python 2.7 Any help? thanks!
import datetime
class User(object):
def __init__(self, full_name, birthday):
self.full_name = full_name
self.birthday = birthday
def calculate_age(self):
"""Return the age"""
yyyy = int(self.birthday[0:4])
mm = int(self.birthday[4:6])
dd = int(self.birthday[6:8])
dob = datetime.date(yyyy, mm, dd)
today = datetime.datetime.today().strftime('%Y%m%d')
today = int(today)
age_in_days = (today - dob)
age_in_years = age_in_days / 365
return int(age_in_years)
def main():
user_enter = raw_input("Enter your b'day:")
User1 = User("susa", user_enter)
print ("your age is" + User1.calculate_age())
if __name__ == "__main__":
main()
Instead of going to all the trouble of converting things to int, you can calculate the difference between two date objects and obtain the result's number of days:
...
dob = datetime.date(yyyy, mm, dd)
today = datetime.datetime.today().date()
age_in_days = (today - dob).days
...
Also, there as some extra things that you can consider reviewing in your code:
Your print is trying to concatenate a string with an int and it won't work.
You can cast the calculate_age() result to fix this:
print("your age is " + str(User1.calculate_age()))
You can use strptime to convert your birthday string input to datetime
and you can call date() to convert your datetime to date. This way you can avoid having to manually breaking your string into parts:
dob = datetime.datetime.strptime(self.birthday, '%Y%m%d').date()

how to get month name from month number in odoo 8

def generate_leave(self, cr, uid,ids, fields, context=None):
if context is None:
context = {}
month_split = self.browse( cr, uid,ids)
print "\n\n\n\n\n\n DATEE",month_split.name
dt = datetime.strptime(month_split.name, "%Y-%m-%d")
year = dt.year
print "\n\n\n\n YER",year
month = dt.month
print "\n\n\n MNTH",month
currentMonth = datetime.now().month
print "\n\n\n\n\n CURR MNTH",currentMonth
date = dt.day
print "\n\n\n\n\n\n DATTE",date
day = dt.day
print "\n\n\n\n\n\n DAYY",day
I have tried for this but i cannot able to achieve it.i have used like "%b" and "%B" but nothing works.
Refer the documentation at http://docs.python.org/2/library/calendar.html
import calendar
month_name= calendar.month_name[3]
print month_name
This works perfectly for me. This returns "March"
In your case you should use like this
month_name= calendar.month_name[dt.month]

Filter the data for particular 15 days of all years in django

I am trying to print the data for particular 15 days of every year.
For example to get the Employee's details who has birthdays with in 15 days.
today = datetime.now()
start_day = today.day
start_month = today.month
end_day = today + timedelta(days=15)
end_date = end_day.day
end_month = end_day.month
user_dob_obj = UserProfile.objects.filter(Q(date_of_birth__month__gte=start_month, date_of_birth__day__gte=start_day) &
Q(date_of_birth__month__lte=end_month, date_of_birth__day__lte=end_date))
Update
Sorry I misunderstood your question. You can use if statement to check if the month is the same 15 days later. Then use the or logical operation to make sure birthdays in current and next month are filtered.
today = datetime.now()
end_date = today + timedelta(days=15)
if today.month == end_date.month:
user_dob_obj = user_dob_obj.filter(date_of_birth__month=today.month, date_of_birth__day__gte=today.day, date_of_birth__day__lte=end_date.day)
else:
user_dob_obj = queryset.filter(Q(date_of_birth__month=today.month, date_of_birth__day__gte=today.day) | Q(date_of_birth__month=end_date.month, date_of_birth__day__lte=end_date.day))

Converting to date format in pandas

I have a dataframe that contains a column which holds:
Date:
31062005
072005
12005
2012
I would like to convert these dates to the format:
Date:
31/06/2005
07/2005
01/2005
2012
What is the simplest way to do this? The fields are not in a date format yet, only strings.
Here:
df = pd.DataFrame(['30/06/2005', '07/2005', '1/2005', '2012'], columns=['Date'])
temp = pd.DataFrame(df['Date'].str.split('/').apply(reversed).tolist())\
.fillna('01')
df['Date'] = pd.to_datetime(temp[0].str.cat(temp[1].str.zfill(2))\
.str.cat(temp[2].str.zfill(2)), format='%Y%m%d')
suppose you write a function
def convert_date(s):
if len(s) == 4:
return s
elif len(s) < 7:
return s[: -4].zfill(2) + '/' + s[-4: ]
else:
return s[: -6].zfill(2) + '/' + s[-6: -4].zfill(2) + '/' + s[-4]
Then if your dates are in df.dates, you can use
>>> df.dates.apply(convert_date)
0 31/06/2
1 07/2005
2 01/2005
3 2012
Name: dates, dtype: object
Note that this converts a string in one form to a string in a different form, meaning you can't really manipulate dates further. If you want to do that, I'd suggest you amend the preceding function to use the appropriate datetime.datetime.strptime for the format matching the length of the string. It could look something like this:
def convert_date(s):
if len(s) == 4:
return datetime.datetime.strptime('%Y')
elif len(s) < 8:
return datetime.datetime.strptime('%m%Y')
else:
return datetime.datetime.strptime('%d%m%Y')
Note that your first date (with the 31 days) seems illegal, though.