python - 将时间四舍五入到微秒

标签 python pandas numpy timestamp unix-timestamp

如何在 python 中将时间戳舍入到微秒?

我有一个这样的时间戳。

   2016-05-07 08:29:58.387888640

我已使用格式对其进行格式化

   %Y-%m-%d %H:%M:%S.%f

来自这样的数据框

  pd.to_datetime(time['Out'], format="%Y-%m-%d %H:%M:%S.%f")

但是,这将其降低到纳秒级别。我希望这能在微秒内完成,但不确定最好的方法是什么。您能告诉我吗?

最佳答案

要显示正确的小数位数,您可以使用时间戳的 strptime 方法 - 其 %f 指令设置为 microseconds .

tstamp = pd.Timestamp('2016-05-07 08:29:58.387888640')
tstamp.strftime("%Y-%m-%d %H:%M:%S.%f")

这只是将等效字符串截断为 '2016-05-07 08:29:58.387888'

如果您担心舍入误差,还应该调用为 pandas 时间戳定义的 round 方法并设置分辨率:

tstamp.round("1 us").strftime("%Y-%m-%d %H:%M:%S.%f")

请注意最后一位数字现在如何正确舍入:'2016-05-07 08:29:58.387889'

关于python - 将时间四舍五入到微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45218994/

相关文章:

python - Django:自定义模板标签,需要 2 个变量

python - Flask 应用程序中的数据未提交到数据库

python - 如何使用 django paginator 在页面上拆分 DataFrame (pandas)?

python - 根据日期从 Pandas Dataframe 中删除行

python - cython 与 python 在 scipy.optimize.fsolve 中的不同结果

javascript - Python Selenium,抓取网页 javascript 表

python - 为什么我会得到 this cannot index with vector containing NA/NaN values 错误

python - Python中的平均计算

python - 将数据分组到数组中(python)

python - Numpy:使用 2D 索引数组访问 2D 数组