How to extract the year from a Python datetime object?


Question

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?

1
78
3/1/2017 5:52:49 PM

Accepted Answer

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.

104
7/15/2009 6:44:31 PM

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

or even (as Lennart suggested)

a = datetime.datetime.now().year

or even

a = datetime.date.today().year

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon