将float数组转换为datetime

时间:2018-07-02 06:06:56

标签: python datetime

我有一个

数组

浮动[130101.34764204, 130101.34764606, 130101.34765007]

在这里,13是2013,01是一月,而01是天。小数表示一天中的这一部分,即.34764204*24 = 8.34 (8:34 AM)。如何将其转换为2013-01-01 8:34的可读日期时间格式。

谢谢。

3 个答案:

答案 0 :(得分:3)

像这样...

new RaisedButton(
       onPressed: () {
          setState(() {
             textController.text = "New text";
          });
       }
    ),

测试代码:

import datetime


def convert_ts(ts):
    ymd, day_part = divmod(ts, 1)
    y, md = divmod(ymd, 10000)
    m, d = divmod(md, 100)
    day_part_secs = day_part * 86400
    return datetime.datetime(int(2000 + y), int(m), int(d)) + datetime.timedelta(seconds=day_part_secs)

输出:

for ts in [
    130101.34764204,
    130101.34764606,
    130101.34765007,
    180702.4,
]:
    print(ts, convert_ts(ts))

答案 1 :(得分:0)

您可以使用正则表达式模式执行此操作,例如,假设l是浮点列表:

import re
from datetime import datetime, timedelta

l = [130101.34764204, 130101.34764606, 130101.34765007]
DAY = 24*60*60

def to_date(f):
    year, month, day, decimal = list(map(int, re.match('(\d{2})(\d{2})(\d{2})\.(\d+)', "{:.8f}".format(f)).groups(1)))
    seconds = decimal*DAY / 10**8
    return datetime(2000+year, month, day) + timedelta(seconds=seconds)
converted_l = map(to_date, l)

结果:

for c in converted_l:
    print(c)
2013-01-01 08:20:36.272256
2013-01-01 08:20:36.619584
2013-01-01 08:20:36.966048

答案 2 :(得分:0)

您可以直接将strptime模块中的timedeltadatetime与数字的整数和小数部分一起使用:

import datetime as DT

lst = [130101.34764204, 130101.34764606, 130101.34765007]

for l in lst:
    d = int(l)
    t = l - int(l)
    print(DT.datetime.strptime(str(d), '%y%m%d') + DT.timedelta(t))

2013-01-01 08:20:36.272256
2013-01-01 08:20:36.619585
2013-01-01 08:20:36.966048