pythondatetime

How to extract the year from a Python datetime object?


I would like to extract the year from the current date using Python.

In C#, this looks like:

 DateTime a = DateTime.Now() 
 a.Year

What is required in Python?


Solution

  • It's in fact almost the same in Python.. :-)

    import datetime
    year = datetime.date.today().year
    

    Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:

    import datetime
    year = datetime.datetime.today().year
    

    (Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).

    One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.