Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdiv Abramson
6,919 PointsDoes Python have any wrapper functions/classes to simplify working with dates and times and associated calculations?
For example, are there Python equivalents for VB date/time functions such as Now(), Date(), Year(), DateAdd() and DateDiff()?
1 Answer
Kenneth Love
Treehouse Guest Teacherdatetime.datetime.now()
gets you now as a datetime
.
datetime.datetime.now().date()
would get you a date
object for now.
datetime.datetime.now().year
would get you the year for now.
timedeltas
are the representation of the difference between two times.
Not sure what DateAdd()
would do.
Adiv Abramson
6,919 PointsAdiv Abramson
6,919 PointsThank you. I guess I was looking for a Python function that, like the VBA Date() function, returns a simple date literal #12/09/2014#. datetime.datetime.now().date(0 yields datetime.date(2014, 12, 9).
I created my own Date() function just now, using the information you provided, that does the trick when I need a date literal:
def Date(): py_date = datetime.datetime.now().date() my_date = "{}/{}/{}".format(py_date.month, py_date.day, py_date.year) return my_date
For example:
Thanks again!
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherWhy not just use the abilities of the
datetime
ordate
classes?That'll return a
date
object. Of course, don't really need the constructor since you're just doing exactly what the class's method already does.