我正在尝试将 datetime.time 字符串转换为等于 python 中的总微秒数的整数。
# my input
>>> mark_raw = '00:01:00.420000' # 0 hr, 1 min, 0 sec, 42 ms
# my desired output
>>> mark_time
60420000
我当前的计划找到自纪元以来的日期时间和自纪元以来的日期之间的差异
# 0 hr, 1 min, 0 sec, 42 ms
>>> mark_raw = '00:01:00.420000'
>>> mark_dt = datetime.strptime(mark_raw, '%H:%M:%S.%f')
>>> mark_dt
datetime.datetime(1900, 1, 1, 0, 1, 0, 420000)
>>> mark_date = mark_dt.date()
>>> mark_date
datetime.date(1900, 1, 1)
>>> dt_epoch = calendar.timegm(mark_dt.timetuple()) * 1000
>>> dt_epoch
-2208988740000
>>> date_epoch = calendar.timegm(mark_date.timetuple()) * 1000
>>> date_epoch
-2208988800000
>>> mark_time = dt_epoch - date_epoch
>>> mark_time
60000
不确定为什么我会得到 60000
微秒。也许是四舍五入的问题?我假设 datetime.date(1900, 1, 1)
等于 datetime.date(1900, 1, 1, 0, 0, 0, 0)
但也许是这样事实并非如此。
唯一的要求是将原始时间字符串获取到微秒,对任何其他策略开放,并且感谢任何帮助!
最佳答案
不匹配的原因是,
>>> mark_dt.timetuple()
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=1, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>> mark_date.timetuple()
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
您可以在这里看到差异! mark_dt.timetuple()
中的 tm_min=1
和 mark_date.timetuple()
中的 tm_min=0
并且,
dt_epoch = calendar.timegm(mark_dt.timetuple())
print dt_epoch
date_epoch = calendar.timegm(mark_date.timetuple())
print date_epoch
mark_time = dt_epoch - date_epoch
print mark_time
将打印
-2208988740
-2208988800
60
从而体现出tm_min = 1和0时两个结果的差异!
获取微秒
并且,如果您想获取微秒,请获取纪元的时间增量,找到总秒数,然后将其乘以 10^-6 即 1e6
# 0 hr, 1 min, 0 sec, 42 ms
import datetime
import calendar
mark_raw = '00:01:00.420000'
mark_dt = datetime.datetime.strptime(mark_raw, '%H:%M:%S.%f')
mark_date = mark_dt.date()
epoch_datetime=datetime.datetime(
year=mark_date.year,
month=mark_date.month,
day=mark_date.day,
)
print (mark_dt - epoch_datetime).total_seconds()*(1000000)
#print (mark_dt - epoch_datetime).total_seconds()*ie6
输出:
60420000.0
希望对你有帮助!
关于python - 将自纪元以来的时间字符串存储到 μ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042184/