How to extract the year from a Python datetime object?

后端 未结 4 1235
野的像风
野的像风 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

    The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.

    > ipython
    import Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
    Type "copyright", "credits" or "license" for more information.
    
    IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
    ?         -> Introduction and overview of IPython's features.
    %quickref -> Quick reference.
    help      -> Python's own help system.
    object?   -> Details about 'object'. ?object also works, ?? prints more.
    
    In [1]: import datetime
    In [2]: now=datetime.datetime.now()
    In [3]: now.
    

    press tab a few times and you'll be prompted with the members of the "now" object:

    now.__add__           now.__gt__            now.__radd__          now.__sub__           now.fromordinal       now.microsecond       now.second            now.toordinal         now.weekday
    now.__class__         now.__hash__          now.__reduce__        now.astimezone        now.fromtimestamp     now.min               now.strftime          now.tzinfo            now.year
    now.__delattr__       now.__init__          now.__reduce_ex__     now.combine           now.hour              now.minute            now.strptime          now.tzname
    now.__doc__           now.__le__            now.__repr__          now.ctime             now.isocalendar       now.month             now.time              now.utcfromtimestamp
    now.__eq__            now.__lt__            now.__rsub__          now.date              now.isoformat         now.now               now.timetuple         now.utcnow
    now.__ge__            now.__ne__            now.__setattr__       now.day               now.isoweekday        now.replace           now.timetz            now.utcoffset
    now.__getattribute__  now.__new__           now.__str__           now.dst               now.max               now.resolution        now.today             now.utctimetuple
    

    and you'll see that now.year is a member of the "now" object.

提交回复
热议问题