【问题标题】:How to get seconds time using strptime from a list如何使用列表中的 strptime 获取秒时间
【发布时间】:2020-05-13 10:56:54
【问题描述】:

我需要在 Python 中在几秒钟内转换一个列表。名单如下:

[27.0, 2.0, 2019.0, 19.0, 59.0, 59.99]

即日、月、年、时、分、秒。

我尝试将datetime.strptime转换成字符串后使用,但是返回错误ValueError: time data '...' does not match format...

【问题讨论】:

  • 显示想要的结果和你的代码。
  • 标题误导;这与strptime 无关。它应该类似于“如何从列表中创建日期时间对象”。如何获得自纪元以来的秒数,例如here.

标签: python date datetime time


【解决方案1】:

使用日期时间但解析字段

字段必须是 int(所以从浮点数转换)

from datetime import datetime

d = [27.0, 2.0, 2019.0, 19.0, 59.0, 59.99]

date = datetime(year = int(d[2]), month = int(d[1]), day=int(d[0]),
             hour = int(d[3]), minute = int(d[4]), second=int(d[5]),
             microsecond= int(1e6*(d[5]-int(d[5]))))

print(date)
# Output: 2019-02-27 19:59:59.990000

print((date-datetime(1970,1,1)).total_seconds()) # Seconds since Jan 1, 1970
                                                 # i.e. Unix time in seconds
# Output: 1551297599.99

【讨论】:

  • 它不返回毫秒 :( 那么如何将日期转换为秒?
  • @Kitama--添加了自 1970 年 1 月 1 日以来的秒数(即 Unix 时间秒数)
【解决方案2】:

你可以在 python 中尝试 datetime 包,如下所示

import datetime
l = [27.0, 2.0, 2019.0, 19.0, 59.0, 59.99]
l_int = list(map(int,l))

d = datetime.datetime(l_int[2],l_int[1],l_int[0], l_int[3], l_int[4],l_int[5])
print(d)

#2019-02-27 19:59:59

【讨论】:

  • 在你的列表中你没有微秒
  • 看看59.99 - .99 是几分之一秒,您必须将其转换为微秒,请参阅@DarryIG 的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
相关资源
最近更新 更多