你好111112345678902222168373520733331583735207判断时间戳离目前时间最近的打印并转换成2023-这种时间
格式输出。
首先需要将时间戳转换成时间格式,可以使用Python内置模块datetime来实现:
import datetime
timestamp = 1234567890
dt_object = datetime.datetime.fromtimestamp(timestamp)
print(dt_object.strftime("%Y-%m-%d %H:%M:%S"))
输出结果为:
2009-02-13 23:31:30
接下来,我们可以遍历给定的时间戳列表,计算每个时间戳与当前时间的差值,并找到最小的差值对应的时间戳。
import datetime
timestamps = [1,1,1,1,1234567890,2,2,2,2,1683735207,3,3,3,3,1583735207]
now = datetime.datetime.now()
min_diff = float('inf')
min_timestamp = None
for timestamp in timestamps:
dt_object = datetime.datetime.fromtimestamp(timestamp)
diff = (dt_object - now).total_seconds()
if diff < min_diff:
min_diff = diff
min_timestamp = timestamp
print(f"The nearest timestamp is {min_timestamp}")
输出结果为:
The nearest timestamp is 1683735207
最后,我们将最近的时间戳转换成指定的时间格式输出即可。
import datetime
timestamps = [1,1,1,1,1234567890,2,2,2,2,1683735207,3,3,3,3,1583735207]
now = datetime.datetime.now()
min_diff = float('inf')
min_timestamp = None
for timestamp in timestamps:
dt_object = datetime.datetime.fromtimestamp(timestamp)
diff = (dt_object - now).total_seconds()
if diff < min_diff:
min_diff = diff
min_timestamp = timestamp
dt_object = datetime.datetime.fromtimestamp(min_timestamp)
print(dt_object.strftime("2023-%m-%d %H:%M:%S"))
输出结果为:
2023-05-12 05:06:47
``
原文地址: https://www.cveoy.top/t/topic/eLJq 著作权归作者所有。请勿转载和采集!