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() 

What is required in Python?

3/1/2017 5:52:49 PM

Accepted Answer

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

import datetime
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 =

(Obviously no different, but you can store 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.

7/15/2009 6:44:31 PM

import datetime
a =

or even (as Lennart suggested)

a =

or even

a =

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