【问题标题】:How to extract the year from a Python datetime object?如何从 Python 日期时间对象中提取年份?
【发布时间】:2010-11-11 02:44:18
【问题描述】:

我想使用 Python 从当前日期中提取年份。

在 C# 中,这看起来像:

 DateTime a = DateTime.Now() 
 a.Year

Python 需要什么?

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    实际上在 Python 中几乎是一样的.. :-)

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

    当然,日期没有关联的时间,所以如果你也关心它,你可以用一个完整的日期时间对象做同样的事情:

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

    (显然没有什么不同,当然,您可以在获取年份之前将 datetime.datetime.today() 存储在一个变量中)。

    需要注意的一个关键点是,在某些 python 版本(我认为是 2.5.x 树)中,32 位和 64 位 python 之间的时间分量可能不同。因此,您会在某些 64 位平台上找到类似小时/分钟/秒的信息,而在 32 位平台上您会看到小时/分钟/秒。

    【讨论】:

    • datetime.datetime.today().year 不适用于 Python 3。它返回错误 AttributeError: type object 'datetime.datetime' has no attribute '日期时间'。我不得不使用 datetime.today().year
    • @twumm,那是因为您将日期时间导入为“从日期时间导入日期时间”。如果您只完成了“导入日期时间”,则该解决方案将正常工作。它和你拥有的完全一样。
    【解决方案2】:
    import datetime
    a = datetime.datetime.today().year
    

    甚至(如Lennart suggested

    a = datetime.datetime.now().year
    

    甚至

    a = datetime.date.today().year
    

    【讨论】:

    • 虽然 now() 在日期时间感觉更自然。 datetime.date.today().year,也许吧。 :)
    • 我没有想到这一点,我想它确实感觉更“准确”的时间,其中 today() 似乎意味着精确的日子。奇怪的是(至少在 2.5.4 中) datetime.today() 和 datetime.now() 做同样的事情
    • 它们不太一样,datetime.now() 接受时区对象,而 datetime.today() 只是调用 fromtimestamp(time.time()),所以 today() 总是使用 Python 认为的本地时区,而你可以让 now() 告诉你更有趣的事情。
    【解决方案3】:

    这个问题的其他答案似乎恰到好处。现在你如何在没有堆栈溢出的情况下自己解决这个问题?查看IPython,这是一个具有选项卡自动完成功能的交互式 Python shell。

    > 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.
    

    按 Tab 几次,系统会提示您“现在”对象的成员:

    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
    

    您会看到 now.year 是“now”对象的成员。

    【讨论】:

    • 另外,这个:docs.python.org/library/datatypes.html 不过谢谢,我不知道 IPython
    • 感谢解决问题——补充实际解决方案。
    • 对于那些不想安装 ipython 的人,你可以用 dir 包装任何函数或类来查看可能的方法和属性。像,dir(datetime.datetime.now) 会为您提供可用的功能,例如 ipython 中的按 tab 键。
    【解决方案4】:

    如果您想要(未知)日期时间对象中的年份:

    tijd = datetime.datetime(9999, 12, 31, 23, 59, 59)
    
    >>> tijd.timetuple()
    time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1)
    >>> tijd.timetuple().tm_year
    9999
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-05
      • 2019-01-07
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2022-11-16
      • 2021-11-04
      相关资源
      最近更新 更多