Pramod
Pramod

Reputation: 89

Convert array of float to datetime

I have an array of

float [130101.34764204, 130101.34764606, 130101.34765007].

Here, 13 is 2013, 01 is January and 01 is the day. And decimal represents the part of the day, i.e .34764204*24 = 8.34 (8:34 AM). How to convert this to the readable date time format of 2013-01-01 8:34.

Thank you in advance.

Upvotes: 0

Views: 4562

Answers (3)

hamza tuna
hamza tuna

Reputation: 1497

You can use regex pattern to do this For example suppose l is list of floats:

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)

Result:

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

Upvotes: 0

SpghttCd
SpghttCd

Reputation: 10860

You can use strptime and timedelta from datetime module directly with the integer and the fractional part of the numbers:

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

Upvotes: 0

AKX
AKX

Reputation: 168843

Something like this...

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)

Test code:

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

Output:

130101.34764204 2013-01-01 08:20:36.272256
130101.34764606 2013-01-01 08:20:36.619585
130101.34765007 2013-01-01 08:20:36.966048
180702.4 2018-07-02 09:35:59.999999

Upvotes: 4

Related Questions