如何从Python日期时间对象中提取年份?

2020/11/30 15:31 · python ·  · 0评论

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

在C#中,这看起来像:

 DateTime a = DateTime.Now() 
 a.Year

Python需要什么?

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

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

当然,日期没有时间关联,因此,如果您也很在意,您可以使用完整的datetime对象进行相同的操作:

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

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

需要注意的一件事是在某些python版本(我认为是2.5.x树)中,时间分量在32位和64位python之间可能有所不同。因此,在某些64位平台上,您会发现诸如小时/分钟/秒之类的信息,而在32位平台上,您会发现时/分/秒。

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

甚至(如Lennart建议的

a = datetime.datetime.now().year

甚至

a = datetime.date.today().year

这个问题的其他答案似乎很快就到了。现在,您如何自己解决这个问题而又没有堆栈溢出?查看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”对象的成员:

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”对象的成员。

如果要从(未知)日期时间对象中获得年份:

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
本文地址:http://python.askforanswer.com/ruhecongpythonriqishijianduixiangzhongtiqunianfen.html
文章标签: ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!