How to extract the year from a Python datetime object?

后端 未结 4 1242
野的像风
野的像风 2021-01-30 12:22

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

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 12:51

    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.

提交回复
热议问题