【问题标题】:Converting string with decimals into datetime [duplicate]将带小数的字符串转换为日期时间[重复]
【发布时间】:2018-10-18 14:03:40
【问题描述】:

这个问题和this SO很像,但是我的数据在表格里:

'13-04-2018 14:06:26.866'
'13-04-2018 14:06:27.131'
'13-04-2018 14:06:27.404'
'13-04-2018 14:06:27.674'
...

即秒数以小数形式给出。我对datetime documentation 的阅读表明它不支持这种格式,所以我不确定如何最好地进行。

【问题讨论】:

  • 您在问题中链接的问题完美地描述了将字符串转换为时间所需的两个参数。
  • @chrisz 我没看到。使用什么参数将秒读为浮点数?
  • @TokeFaurby 您使用%S 表示秒的整数部分,使用%f 表示秒的小数部分。 “带分数的秒数”或“作为浮点数的秒数”没有格式说明符。
  • @Alfe stackoverflow.com/questions/698223/… 更好的欺骗目标?
  • @chrisz 是的,好多了:)

标签: python datetime time


【解决方案1】:

看来你需要

  • .%f == Microsecond as a decimal number, zero-padded on the left.

例如:

import datetime
s = '13-04-2018 14:06:26.866'
print(datetime.datetime.strptime(s, "%d-%m-%Y %H:%M:%S.%f"))

输出:

2018-04-13 14:06:26.866000

【讨论】:

  • 啊,你是对的。 “左侧填充”让我感到困惑,但它有效
猜你喜欢
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 2020-01-24
  • 1970-01-01
相关资源
最近更新 更多