def checkage(year,month,day):
today_day=11
today_month=6
today_year=2021
age=((today_year*365)+
(today_month*30)+today_day)-
((year*365)+(month*30)+day)
print(age//12,"year",(age-
((age//12)*365))//30,"month",
(age-((age-
((age//12)*365))//30)*30,"days")
checkage(1996,12,11)
Python :In the last line it is showing syntax error.why?
You need one more ) after ..."days")
(that clears the syntax error, at least )
You are not correctly opening and closing brackets in your code. If you want a line of code to span across more lines, you need to make use of an additional bracket. You should also make use of indents to make your code more readable like so:
def checkage(year,month,day):
today_day=11
today_month=6
today_year=2021
age=(((today_year*365)+
(today_month*30)+today_day)-
((year*365)+(month*30)+day))
print(age//12,
"year",
((age-((age//12)*365))//30),
"month",
(age-((age-((age//12)*365))//30)*30),"days")
checkage(1996,12,11)
output:
745 year -8766 month 271925 days
This doesnt seem to be doing the correct calculation either. If you want to work with dates you should consider the datetime library
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print(calculate_age(date(1996, 12, 11)))
output:
24
You are missing a ) in your last print statement.
def checkage(year,month,day):
today_day=11
today_month=6
today_year=2021
age=((today_year*365)+ (today_month*30)+today_day)- ((year*365)+(month*30)+day)
print(age//12,"year",(age- ((age//12)*365))//30,"month", (age-((age-((age//12)*365))//30)*30,"days"))
checkage(1991,12,21)
Output
896 year -10543 month (327050, 'days')
P.S. Your logic isnt right, it takes even 51 as month which is incorrect.
You are just missing the closing parenthesis of the print function;
def checkage(year,month,day):
today_day=11
today_month=6
today_year=2021
age=((today_year*365)+
(today_month*30)+today_day)-((year*365)+(month*30)+day)
print(age//12,"year",(age-((age//12)*365))//30,"month",(age-((age-((age//12)*365))//30)*30,"days"))
checkage(1996,12,11)
Related
I am trying to generate a date with range but the time is not showing. The code is as follows:
def date_range(start, end, step: datetime.timedelta):
while start < end:
yield start
start += step
for d in date_range(
start=datetime.date(2019, 1, 1),
end=datetime.date(2019, 1, 15),
step=datetime.timedelta(days=7),
):
print(d)
>>>2019-01-01
>>>2019-01-08
The code shows the date only without the time. Why???
You are using datetime.date() which, according to the Python documentation here does not include time information - it just sets the hours/minutes/seconds to 0.
I think you want to use datetime.datetime() which does include time information.
See the Python documentation on datetime.datetime() for more information.
I am trying to convert a yyyyww which is actually starting as a string object I think at is like 201731. I want to capture the last 6 weeks including its self.
def generate_6_last_week(yearweek):
weeks = [int(yearweek)]
date = time.mktime(datetime.strptime(str(yearweek)+"0","%Y%W%w").timetuple())
for i in range(1,6):
date = date-604800 # 60*60*24*7
weeks.append(int(datetime.fromtimestamp(int(date)).strftime('%Y%W')))
return weeks
generate_6_last_week(201731)
so the output for 201731 should be:
[201731, 201730, 201729, 201728, 201727, 201726]
and this seems to work, the problem is if i test it with a crossover year like 201702 it returns this:
[201702, 201701, 201700, 201651, 201650, 201649]
Which also looks pretty good, but I need it in ISO weeks so there shouldnt be a week 00 I think and the last week of a year should be either 53 or 52 but not the 51.
Any ideas how to adapt this?
This requires the "isoweek" package to be installed but gave me what i want with some manipulation of the format of my str YYYYWW and works well with the crossover years.
from isoweek import Week
yearweek = "201702"
weeks = [int(yearweek)]
x = 1
for i in range(5):
week = int(str(Week(int(yearweek[:4]), int(yearweek[-2:])-x)).replace("W",""))
weeks.append(week)
x +=1
print(weeks)
or in a function format.
def generate_6_last_week(yearweek):
weeks = [int(yearweek)]
x = 1
for i in range(5):
week = int(str(Week(int(yearweek[:4]), int(yearweek[-2:])-x)).replace("W",""))
weeks.append(week)
x +=1
print(weeks)
generate_6_last_week("201702")
I do not know anything about striptime(). So I have solved the problem by writing my own code. Here's the code:
date=input()
a=int(date[0:4])
b=int(date[4:])
k=5-b
finallist=[]
def m(x,y):
return(x-y)
if b>=5:
date=int(date)
finallist=[date,date-1,date-2,date-3,date-4,date-5]
print(finallist)
else:
date=int(date)
for i in range(b+1):
finallist.append(date)
date-=1
a-=1
b=52
date=int(str(a)+str(b))
for i in range(k):
finallist.append(date)
date-=1
print(finallist)
201700 gives [201700, 201652, 201651, 201650, 201649, 201648]
201702 gives [201702, 201701, 201700, 201652, 201651, 201650]
ALITER: There's a much easier way to do this. Just add 1 to those specific list items in your list :p
I have a Python script that generates .csv files from other data sources.
Currently, an error happens when the user manually adds a space to a date by accident. Instead of inputting the date as "1/13/17", a space may be added at the front (" 1/13/17") so that there's a space in front of the month.
I've included the relevant part of my Python script below:
def processDateStamp(sourceStamp):
matchObj = re.match(r'^(\d+)/(\d+)/(\d+)\s', sourceStamp)
(month, day, year) = (matchObj.group(1), matchObj.group(2), matchObj.group(3))
return "%s/%s/%s" % (month, day, year)
How do I trim the space issue in front of month and possibly on other components of the date (the day and year) as well for the future?
Thanks in advance.
Since you're dealing with dates, it might be more appropriate to use datetime.strptime than regex here. There are two advantages of this approach:
It makes it slightly clearer to anyone reading that you're trying to parse dates.
Your code will be more prone to throw exceptions when trying to parse data that doesn't represent dates, or represent dates in an incorrect format - this is good because it helps you catch and address issues that might otherwise go unnoticed.
Here's the code:
from datetime import datetime
def processDateStamp(sourceStamp):
date = datetime.strptime(sourceStamp.replace(' ', ''), '%M/%d/%y')
return '{}/{}/{}'.format(date.month, date.day, date.year)
if __name__ == '__main__':
print(processDateStamp('1/13/17')) # 1/13/17
print(processDateStamp(' 1/13/17')) # 1/13/17
print(processDateStamp(' 1 /13 /17')) # 1/13/17
You also can use parser from python-dateutil library. The main benefit you will get - it can recognize the datetime format for you (sometimes it may be useful):
from dateutil import parser
from datetime import datetime
def processDateTimeStamp(sourceStamp):
dt = parser.parse(sourceStamp)
return dt.strftime("%m/%d/%y")
processDateTimeStamp(" 1 /13 / 17") # returns 01/13/17
processDateTimeStamp(" jan / 13 / 17")
processDateTimeStamp(" 1 - 13 - 17")
processDateTimeStamp(" 1 .13 .17")
Once again, a perfect opportunity to use split, strip, and join:
def remove_spaces(date_string):
date_list = date_string.split('/')
result = '/'.join(x.strip() for x in date_list)
return result
Examples
In [7]: remove_spaces('1/13/17')
Out[7]: '1/13/17'
In [8]: remove_spaces(' 1/13/17')
Out[8]: '1/13/17'
In [9]: remove_spaces(' 1/ 13/17')
Out[9]: '1/13/17'
I'm trying to do a search between two dates with sqlalchemy. If I used static dates will be this way.
def secondExercise():
for instance in session.query(Puppy.name, Puppy.weight, Puppy.dateOfBirth).\
filter(Puppy.dateOfBirth <= '2015-08-31', Puppy.dateOfBirth >= '2015-02-25' ).order_by(desc("dateOfBirth")):
print instance
Manipulating dates in python is quite easy.
today = date.today().strftime("%Y/%m/%d")
sixthmonth = date(date.today().year, date.today().month-6,date.today().day).strftime("%Y/%m/%d")
The problem is, I don't know how to implement this as parameter. Any help with this?
for instance in session.query(Puppy.name, Puppy.weight, Puppy.dateOfBirth).\
filter(Puppy.dateOfBirth <= today, Puppy.dateOfBirth >= sixthmonth ).order_by(desc("dateOfBirth")):
SQLAlchemy supports comparison by datetime.date() and datetime.datetime() objects.
http://docs.sqlalchemy.org/en/rel_1_0/core/type_basics.html?highlight=datetime#sqlalchemy.types.DateTime
You can expose these as parameters (replace your_query with all the stuff you want to be constant and not parametrized):
six_months_ago = datetime.datetime.today() - datetime.timedelta(180)
today = datetime.datetime.today()
def query_puppies(birth_date=six_months_ago):
for puppy in your_query.filter(Puppy.dateOfBirth.between(birthdate, today)):
print puppy.name # for example..
Also note the usage of the between clause for some extra awesomeness :)
but two seperate clasuses using <= and >= would also work.
cheers
In Python, what is the best way to get the
RFC 3339 YYYY-MM-DD text from the output of gtk.Calendar::get_date()?
Thanks to Mark and treeface for the solutions, but it seems I've invented a better one:
year, month, day = cal.get_date()
return '{0:04d}-{1:02d}-{2:02d}'.format(year, month+1, day)
This solution is shorter, easier to understand (in my opinion), and I believe takes less processing as it cuts out the stage where the tuple is converted into UNIX time.
According to the docs, the get_date returns a tuple of (year,month,day), where month 0 to 11 and day is 1 to 31, so:
import datetime
dtTuple = calControl.get_date()
dtObj = datetime.datetime(dtTuple[0], dtTuple[1] + 1, dtTuple[2]) #add one to month to make it 1 to 12
print dtObj.strftime("%Y-%m-%d")
This might be useful to you:
http://www.tutorialspoint.com/python/time_strftime.htm
I've also just looked around for this gtk get_date method and I was able to find some code that handles it like this:
//here replace "self.window.get_date()" with "gtk.Calendar::get_date()"
year, month, day = self.window.get_date()
mytime = time.mktime((year, month+1, day, 0, 0, 0, 0, 0, 0))
return time.strftime("%x", time.gmtime(mytime))
So just replace "%x" with "%G-%m-%d" and I think it would work. Or at least it's worth a try.