Python datetime quiz

Without looking at the documentation (or running the code), describe the outputs of the following 4 function calls:

from datetime import datetime

datetime.datetime.now()
datetime.datetime.today()
datetime.datetime.now().date()
datetime.datetime.today().date()

Post your answers as a comment.

This entry was posted in General and tagged , . Bookmark the permalink.

3 Responses to Python datetime quiz

  1. Stephen says:

    I’ll play! I don’t know python though.

    datetime.datetime.now() = 40422.6593443287
    datetime.datetime.today() = 40422
    datetime.datetime.now().date() = 0
    datetime.datetime.today().date() = 40422

    How did I do?

  2. slacy says:

    You did okay, but since you’re not familiar with the datetime library, you got the return values right. I’ll translate your results into:

    now() = “date and time”
    today() = “date only”
    now().date() = “nonsensical”
    today().date() = “date only”

    The funny thing is that the main difference between now() and today() is the timezone. For most installations, they return the exact same value. So, even though you would think today() was a date, it’s actually a date + time.

    The date() function strips off the time component (as you assumed), and returns an object with “date only”. So, now().date() and today().date() are the same thing.

    Here are the official results:

    In [8]: datetime.datetime.now()
    Out[8]: datetime.datetime(2010, 9, 2, 13, 6, 53, 332016)

    In [9]: datetime.datetime.today()
    Out[9]: datetime.datetime(2010, 9, 2, 13, 6, 55, 153545)

    In [10]: datetime.datetime.now().date()
    Out[10]: datetime.date(2010, 9, 2)

    In [11]: datetime.datetime.today().date()
    Out[11]: datetime.date(2010, 9, 2)

  3. Stephen says:

    That’s not intuitive. Who would expect the first two results?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>