Python中如何将DateTime对象转回带微秒精度的原始Epoch时间戳?
解决DateTime对象转Epoch浮点数的精度丢失问题
问题原因
time.mktime()配合timetuple()会丢失微秒精度,因为timetuple()返回的结构化时间对象(struct_time)只保留到秒级,微秒信息会被直接丢弃,所以转换后只能得到整数部分的时间戳。
解决方案
方法1:使用datetime.timestamp()方法(推荐)
Python 3.3及以上版本的datetime对象自带timestamp()方法,能直接返回包含微秒精度的Epoch浮点数,完全匹配原始时间戳的精度:
import datetime # 假设my_DateTime_obj是已创建的带微秒的DateTime对象 epoch_timestamp = my_DateTime_obj.timestamp() print(epoch_timestamp) >>1661796943.881677
方法2:手动计算秒数+微秒
如果使用的Python版本低于3.3,可以手动提取秒数和微秒部分相加:
import time # 先获取秒级时间戳 seconds = time.mktime(my_DateTime_obj.timetuple()) # 加上微秒部分(微秒转秒) microseconds = my_DateTime_obj.microsecond / 1e6 epoch_timestamp = seconds + microseconds print(epoch_timestamp) >>1661796943.881677
补充说明
timetuple():将datetime对象转换为struct_time,这个结构仅包含年、月、日、时、分、秒等整数信息,不存储微秒,所以用它转换必然丢失精度。time.mktime():将struct_time转换为Epoch秒数,返回的是浮点数,但因为输入的结构没有微秒,所以小数部分为0。
内容的提问来源于stack exchange,提问作者Marc B. Hankin
相关产品推荐
相关产品推荐

