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 trial

Python Dates and Times in Python (2014) Dates and Times Manipulating Time Already

Does 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
STAFF
Kenneth Love
Treehouse Guest Teacher

datetime.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.

Thank 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:

Date() '12/9/2014'

Thanks again!

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Why not just use the abilities of the datetime or date classes?

def Date(date_string):
    return datetime.date.strptime(date_string, '%m/%d/%Y')

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.