Python datetime.utcfromtimestamp()类

Pythondatetime.utcfromtimestamp() 类是一种在Python中查找日期和时间的有效方法。它以UTC DateTime 的格式表示时间,对应于POSIX 的时间戳。

时间戳的范围通常限制在1970年到2038年的年份。

Pythondatetime.utcfromtimestamp() 类的语法

datetime.utcfromtimestamp(timestamp)

参数

timestamp – 一个浮点数,代表自某一事件发生后的时间,单位为秒。

返回值

该类不返回一个值。

例1:在Python中使用datetime.utcfromtimestamp()

from datetime import datetime
datetime_object = datetime.utcfromtimestamp(1471290435.0)
print("The time and date in UTC, depending on the timestamp, is: ", datetime_object)

输出:

The time and date in UTC, depending on the timestamp, is:  2016-08-15 19:47:15

得到的日期和时间与系统的当前日期和时间是天真的。

例2:在datetime.utcfromtimestamp() 类中输入超出范围的值

from datetime import datetime
datetime_object = datetime.utcfromtimestamp(1471296735240435.0)
print("The time and date in UTC, depending on the timestamp, is: ", datetime_object)

输出结果:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    datetime_object = datetime.utcfromtimestamp(1471296735240435.0)
ValueError: year 46625507 is out of range

在3.3版本中,如果时间戳超出范围,不被平台C的gmtime() 函数所支持,就会产生一个OverflowError

例3:显示datetime.utcfromtimestamp() 类的组件

from datetime import datetime
datetime_object = datetime.utcfromtimestamp(1471290435.0)
print("The time and date in UTC, depending on the timestamp, is: ", datetime_object)
print("year = ", datetime_object.year)
print("month =", datetime_object.month)
print("day =", datetime_object.day)
print("hour =", datetime_object.hour)
print("minute =", datetime_object.minute)
print("second =", datetime_object.second)

输出:

The time and date in UTC, depending on the timestamp, is:  2016-08-15 19:47:15
year =  2016
month = 8
day = 15
hour = 19
minute = 47
second = 15

我们可以使用. 点符号来访问datetime 对象的特定部分。