如何在 Python 中使用 datetime.fromtimestamp() 方法转换时间戳

datetime.fromtimestamp(timestamp) 是 Python datetime 模块中的一个静态方法,用于将给定的时间戳(通常是表示自1970年1月1日 00:00:00(UTC)以来经过的秒数)转换为一个表示本地日期和时间的 datetime 对象。

使用方法

import datetime

timestamp = 1660943143.123  # 示例时间戳,浮点数形式,包含小数部分代表毫秒或微秒
local_datetime = datetime.datetime.fromtimestamp(timestamp)
print(local_datetime)

输出类似于:

2022-08-20 05:05:43.123000

参数说明

  • timestamp:一个浮点数或整数,表示自1970年1月1日 00:00:00(UTC)以来经过的秒数。浮点数形式的时间戳可能包含小数部分,用于表示毫秒或微秒级别的精度。

注意事项

  1. 本地时间:fromtimestamp() 方法返回的是基于本地时区的日期和时间。这意味着结果会受到运行该代码的计算机系统的时区设置影响。如果你需要获取特定时区的日期和时间,可以结合使用 pytz 或 zoneinfo 库(Python 3.9+)来处理时区转换。
  2. 时间戳类型:尽管许多系统使用秒为单位的时间戳,但有些情况下时间戳可能包含小数部分,表示更细粒度的时间单位(如毫秒或微秒)。Python 的 datetime 模块能够处理包含小数部分的时间戳,将其转换为相应的 datetime 对象。
  3. 异常处理:传入的时间戳如果超出可表示的日期范围(通常为1970年至某个远期日期),fromtimestamp() 方法将抛出 OverflowError 异常。确保提供的时间戳值合理。

示例代码

import datetime

# 示例时间戳(秒级别)
timestamp_seconds = 1660943143
local_datetime_seconds = datetime.datetime.fromtimestamp(timestamp_seconds)
print(f"Local datetime (seconds): {local_datetime_seconds}")

# 示例时间戳(毫秒级别)
timestamp_milliseconds = 1660943143123
local_datetime_milliseconds = datetime.datetime.fromtimestamp(timestamp_milliseconds / 1000)  # 除以1000转为秒
print(f"Local datetime (milliseconds): {local_datetime_milliseconds}")

# 示例时间戳(微秒级别)
timestamp_microseconds = 1660943143123456
local_datetime_microseconds = datetime.datetime.fromtimestamp(timestamp_microseconds / 1e6)  # 除以1e6转为秒
print(f"Local datetime (microseconds): {local_datetime_microseconds}")

总结来说,datetime.fromtimestamp(timestamp) 方法允许你将一个时间戳值转换为 Python datetime 对象,便于进一步进行日期和时间相关的操作。在处理跨时区或需要特定时区日期时间的场景时,需要注意结合时区处理库进行调整。


存档地址:https://www.yuque.com/worthstudy/study/fxqvvrtb6m98v3lh?singleDoc# 《datetime.fromtimestamp(timestamp) 方法》

© 版权声明
THE END
喜欢就点赞支持一下吧,如果觉得不错或日后有所需要,可以收藏文章和关注作者哦。
点赞0打赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容