python timestamp 时间区间,python datetime fromtimestamp产生valueerror年超出范围

When attempting to convert a float formatted timestamp e.g 1437506779950.0 into a datetime object, I'm getting a ValueError "year is out of range".

This code that I used, was working not 3 months ago. Revisiting it now, strangely is now throwing this error yet nothing in the code base has changed, only the data that is being passed to it, and the only data that has changed there is obviously the timestamp.

>>> f = 1437506779950.0

>>> datetime.datetime.fromtimestamp(float(f))

Traceback (most recent call last):

File "", line 1, in

ValueError: year is out of range

I can't understand what would have changed to make this break?

解决方案

As noted in the answer for this question, this looks like a unit conversion issue. You have to divide your timestamp by 1000 to convert from milliseconds to seconds.

If you want to preserve millisecond precision, instead divide by 1000.0.

### 关于 `datetime` 模块中的 `fromtimestamp` 方法 在 Python 中,`datetime.datetime` 类确实提供了名为 `fromtimestamp` 的类方法用于将时间戳转换成日期时间对象[^2]。然而,在某些情况下可能会遇到错误提示该属性不存在的情况。 #### 可能的原因及解决方案 1. **版本兼容性问题** 如果正在使用的是非常旧的 Python 版本,则可能真的缺少此方法。建议升级到更新版本来解决问题。现代 Python 发行版已经包含了完整的 `datetime` 功能集[^4]。 2. **导入方式不正确** 确认是否正确地从 `datetime` 模块中导入了 `datetime` 类。正确的做法如下所示: ```python from datetime import datetime ts = 1609459200 # Unix 时间戳表示20211月1日零点整 dt = datetime.fromtimestamp(ts) print(dt.strftime('%Y-%m-%d %H:%M:%S')) ``` 3. **处理不同平台的时间差异** 不同操作系统对于本地时间和 UTC 时间有不同的默认设置。为了确保跨平台一致性,可以考虑显式指定时区信息。这里给出一个改进后的例子,它能够适应不同的环境并考虑到时区的影响[^3]: ```python import pytz from datetime import datetime def timestamp_to_datetime(t): """ 将给定的时间戳转换为带有适当时区信息的 datetime 对象。 参数: t (float or int): 输入的时间戳数值。 返回值: datetime: 转换得到的 datetime 实例。 """ if isinstance(t, float) and abs(t) >= 86400: return datetime.fromtimestamp(t).astimezone(pytz.utc) elif isinstance(t, int) and abs(t) < 86400: utc_dt = datetime(1970, 1, 1) + datetime.timedelta(seconds=t) return utc_dt.astimezone(pytz.utc) raise ValueError("Invalid timestamp value.") # 测试代码片段 test_timestamps = [ 1609459200, 1234567890, -1234567890, 86399 # 接近一天的最大秒数 ] for tstmp in test_timestamps: try: converted_date = timestamp_to_datetime(tstmp) print(f"Timestamp {tstmp} -> Date Time {converted_date}") except Exception as e: print(e) ``` 通过上述调整,应该可以在大多数场景下正常调用 `fromtimestamp` 函数而不会报错。如果仍然存在问题,请仔细检查具体的运行上下文以及所使用的 Python 版本号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值