Python Datetime.fromtimestamp()方法

Pythondatetime.fromtimestamp() 方法是一种将时间戳转换为DateTime对象的有效方法。一个时间戳是代表一个特定事件发生的日期和时间的编码信息。

Pythondatetime.fromtimestamp() 方法的语法

datetime.fromtimestamp(datetime_object,tz)

参数

datetime_object 一个需要被转换为时间戳实例的日期和时间对象。
tz 一个可选的参数,默认值为None. ,它代表我们要转换DateTime对象的时区。

返回

这个方法的返回类型是一个叫做dt_object. 的对象,它返回本地的日期和时间(DateTime 对象)。

示例代码:使用datetime.fromtimestamp() 方法工作

from datetime import datetime
timestamp = 1545830077
datetime_object = datetime.fromtimestamp(timestamp)
print("The date and time are ", datetime_object)
print("type(dt_object) =", type(datetime_object))

输出:

The date and time are  2018-12-26 13:14:37
type(dt_object) = <class 'datetime.datetime'>

请注意,上述代码可以用来寻找任何日期和时间,只需使用一个时间戳。

示例代码:在datetime.fromtimestamp() 方法中输入不同的时间戳

from datetime import datetime
timestamp = -67130984480.0
datetime_object = datetime.fromtimestamp(timestamp)
print("The date and time are ", datetime_object)
timestamp = 303059844320.0
datetime_object = datetime.fromtimestamp(timestamp)
print("The date and time are ", datetime_object)

输出:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    datetime_object = datetime.fromtimestamp(timestamp)
ValueError: year -158 is out of range
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    datetime_object = datetime.fromtimestamp(timestamp)
ValueError: year 11573 is out of range

上面的代码对过去很远的时间或未来很远的时间提出了一个OverflowErrorOSError 异常。上述代码在UNIX系统上测试。

示例代码:使用datetime.fromtimestamp() 方法以不同的格式表示一个时间戳

from datetime import datetime
timestamp = 1725309972.357546
datetime_object = datetime.fromtimestamp(timestamp)
string_datetime = datetime_object.strftime("%d-%m-%Y, %H:%M:%S")
print("Format 1:", string_datetime)
string_date = datetime_object.strftime("%d %B, %Y")
print("Format 2:", string_date)
string_time = datetime_object.strftime("%I%p %M:%S")
print("Format 3:", string_time)

输出:

Format 1: 02-09-2024, 20:46:12
Format 2: 02 September, 2024
Format 3: 08PM 46:12

上面的代码可以很容易地将时间戳转换为任何格式。