convert millisecond to datetime in Python

137 Views Asked by At

I have a set of data whose time is esper in milliseconds (time.stamp), where each value represent a misure (10 Hz it's the working time of the instrument):

enter image description here

enter image description here

What I want to do knowing the year, month, day, hour, minutes and seconds of the start of the measurement is to transform into a datetime of the type

yyyy-mm-dd hh:min:sec.milliseconds

I perform this operation with a few lines of code in python by creating the datetime column:

flist = os.listdir(data_files)
for f in flist:
    df = pd.read_csv(data_files + "/" + f)
    yyyymmdd, hhmm, _ = f.split(".")
    yyyy = yyyymmdd[0:4]
    mm = yyyymmdd[4:6]
    dd = yyyymmdd[6:8]
    hh = hhmm[0:2]
    minute = hhmm[2:4]
    lst = []
    for ind in df.index:
        ts: float = df['time.stamp'][ind]
        d = f'{yyyy}-{mm}-{dd} {hh}:{minute}:{0}.{0}'
        dt = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f')
        result = dt + timedelta(milliseconds=ts)
        lst.append(str(result))
    df['datetime'] = lst
    df.to_csv(os.path.normpath(data_dummy_files + "/" + f), index=False)

enter image description here

enter image description here

the problem is the final data is 2021-05-01 00:00:03.599900 This means that about 4 minutes passed between the start and end of the measurements, in reality the instrument was running for about 60 minutes (1 hour).

0

There are 0 best solutions below