Home>

I want to get two kinds of time using datatime in Python and numpy

There are two formats for time data
The data format is
"2020-10-03 00:00:00"
"2020-10-03 00: 00: 00.1"
It looks like this. When it is zero seconds, there are no milliseconds, but in other cases, there are milliseconds.

Error message
time data'"2020-11-01 00:00:00"' does not match format'% Y-% m-% d% H:% M:% S.% f'

Corresponding source code
time_fmt1 ='"' +"% Y-% m-% d% H:% M:% S.% f "+'"'
for i in range (data.shape [0]):
            if len (data [i, 0])<21:
                data [i,0] = data [i,0] + ".0" # if the second does not have decimal value
date_time = [datetime.datetime.strptime (x, time_fmt1) for x in data [:, 0]]
        date_time = np.array ([date_time]). T
What I tried

Judge the presence or absence of milliseconds, and if there are no milliseconds, add'.0' to the end before processing.
Determines the presence or absence of milliseconds and switches the strptime format depending on which one

I'm wondering if either of these can be used, but I tried the former method, but I'm in trouble because I can't. Please lend me some wisdom.

Supplementary information (FW/tool version, etc.)

python 3.

  • Answer # 1

    if len (data [i, 0])<21:
    I don't think it will hit.
    Also
    + ".0"
    You have to remove the last "and then add it.

    TGT_LEN = len ('"2020-10-03 00:00:00"') # 21
    TOP_LEN = len ('"2020-10-03 00:00:00') # 20
    time_fmt1 ='"' +"% Y-% m-% d% H:% M:% S.% f "+'"'
    for i in range (data.shape [0]):
        #if len (data [i, 0])<21:
        if len (data [i, 0])<= TGT_LEN:
            #data [i,0] = data [i,0] + ".0"
            data [i,0] = data [i,0] [: TOP_LEN] +'.0 "'# if the second does not have decimal value
    date_time = [datetime.datetime.strptime (x, time_fmt1) for x in data [:, 0]]
    date_time = np.array ([date_time]). T

  • Answer # 2

    Please use the following function as it is, or arrange it appropriately.

    >>>import numpy as np
    >>>import datetime
    >>>def convdt (x):
    ... time_fmt1 ='% Y-% m-% d% H:% M:% S'
    ... time_fmt2 ='% Y-% m-% d% H:% M:% S.% f'
    ... try:
    ... return datetime.datetime.strptime (x, time_fmt1)
    ... except Exception:
    ... return datetime.datetime.strptime (x, time_fmt2)
    ...
    >>>print (convdt ("2020-10-03 00:00:00"))
    2020-10-03 00:00:00
    >>>print (convdt ("2020-10-03 00: 00: 00.1"))
    2020-10-03 00: 00: 00.100000